I'm reading a binary file using c#. The specification for the file type says there 6 things packed into a byte[8]. However, it says first variable are the 0-19 bits. Second variable 20-39, third 40-59, fourth 60-62 and the 63 bit is is boolean. How do I convert these bits to meaningful data? All these variables are uints except last bit.
Let's say bytes is your byte[8]. Let's also say that bytes is big endian, meaning that the first bit is the most significant ( http://en.wikipedia.org/wiki/Endianness )
0 1 2 3 4 5 6 7
11111111 11111111 11112222 22222222 22222222 33333333 33333333 3333444B
int first = bytes[0] << 12 + bytes[1] << 4 + (bytes[2] >> 4)&0xF;
int second = (bytes[2]&0xF) << 16 + bytes[3] << 8 + bytes[4];
int third = bytes[5] << 12 + bytes[6] << 4 + (bytes[7] >> 4)&0xF;
int fourth = (bytes[7] >> 1)&0x8;
bool flag = bytes[7]&0x1 == 1 ? true : false;
Basically we have two main operations here:
<<
and >>
shift the bits of the left operand left or right by the number of bits in the right operand. So 00101101 >> 4 = 00000010
and 00101101 << 4 = 11010000
&0x?
is a bit mask. & compares every pair of bits, and the result is 1 only if both bits are 1, 0 otherwise. Only the 1s in the mask will be allowed to propagate through, the others will be erased.
00101101&0xF = 00001101
and 00101101&0x1 = 00000001
(note: 0xF is 00001111 and 0x1 is 00000001)
Read about C# operators here: http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.71).aspx
If bytes is little endian then the bit twiddling will be different.