I have been given the following programming task (edited to obscure mission-specifics):
The raw (binary) file (needed for Phase II implementation) can be interrogated to detect if pods are present. Format is dependent on the source of the file – FormatX vs. FormatY. Using a wordsize of 16 bits, the following bit masks can be used to determine presence of pods from the file:
Word # Mask Value Indicates
1 0xFF00 0x8700 Little Endian (Format X)
1 0x00FF 0x0087 Big Endian (Format Y)
13 0x0200 0x0200 right pod installed (Format X)
13 0x000开发者_如何学JAVA2 0x0002 right pod installed (Format Y)
13 0x0100 0x0100 left pod installed (Format X)
13 0x0001 0x0001 left pod installed (Format Y)
How I have approached this problem so far: I have the file on my local file system, so I use System.IO.File.OpenRead to get it into a Stream object. I want to read through the stream 16 bits/2 bytes at a time. For the first "word" of this size, I try applying bitmasks to detect what format I am dealing with. Then I skip forward to the 13th "word" and based on that format, detect right/left pods.
Here's some preliminary code I have written that is not working. I know the file I am reading should be Format Y but my check is not working.
int chunksRead = 0;
int readByte;
while ((readByte = stream.ReadByte()) >= 0)
{
chunksRead++;
if (chunksRead == 1)
{
// Get format
bool isFormatY = (readByte & 0x00FF) == 0x0087;
}
else if (chunksRead == 13)
{
// Check pods
}
else if (chunksRead > 13)
{
break;
}
}
Can anyone see what's wrong with my implementation? How should I account for the 2 byte wordsize?
Edit based on response from @Daniel Hilgarth
Thanks for the quick reply, Daniel. I made a change and it's working for the first word, now:byte[] rawBytes = new byte[stream.Length];
stream.Read(rawBytes, 0, rawBytes.Length);
ushort formatWord = Convert.ToUInt16(rawBytes[0] << 8 | rawBytes[1]);
bool formatCheck = (formatWord & 0x00FF) == 0x0087;
I just need to find an example file that should return a positive result for right/left pod installed to complete this task.
You are mixing bytes and words. The word at position 13 is about whether the left or the right pod is installed. You are reading 12 bytes to get to that position and you are checking the 13th byte. That is only half way.
The same problem is with your format check. You should read the first word (=2 bytes) and check whether it is one of the desired values.
To get a word from two bytes you read, you could use the bit shift operator <<:
ushort yourWord = firstByte << 8 | secondByte;
精彩评论