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.
-
1Little endian or big endian? – Patashu May 15 '13 at 01:30
-
Little Endian is what it says in the specs. – user2383945 May 16 '13 at 02:37
1 Answers
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.

- 21,443
- 3
- 45
- 53
-
Oh wow thanks a lot!! I initially tried int first = (bytes[0] | (bytes[1] >> 8) | (bytes[2] >> 16)) & 1048575; But yours makes more sense! – user2383945 May 15 '13 at 01:42
-
@user2383945 Just verify that the bit packing in `bytes` is what you think it is. If it's not, the logic will be different. – Patashu May 15 '13 at 02:01
-
Okay, I'm still having some trouble and I think it's because I need to do it in little endian. Do I have to reverse the bits? – user2383945 May 16 '13 at 02:16
-
@user2383945 You may have to reverse the bytes, bits or both. See if you can find out what packing is correct (if you can produce binary files of this format with whatever values you want, try changing the values one bit at a time and seeing what changes in the binary file, e.g. with a hex editor) – Patashu May 16 '13 at 02:40