I am trying to parse binary data that I receive in a string. I am not very familiar with bitwise operation.
One of the byte (which I assume is an unsigned short) in my string contains 2 important numbers: the version and a count. Bits 1 to 4 contain the version, bits 5 to 8 contain the count.
So I have an unsigned short
containing开发者_Go百科 the data, how do I obtain two unsigned short containing the 2 information I need.
bit: 1_2_3_4_5_6_7_8_
con: VERSION_COUNT___
Shift and perform AND operation.
int version = value & 0xF;
int count = (value >> 4) & 0xF;
or vice versa. Bits as numbers are right to left - 7-6-5-4-3-2-1-0
unsigned short part1 = data & 0xF; // bits 0..3
unsigned short part2 = (data >> 4) & 0xF; // bits 4..7
I understand that two pieces of information (version and count) are stored as a pair of two nibbles (4-bit pieces) in a single byte so I think you thought of unsigned char
type instead of unsigned short
(in which case you would split it into two bytes). If this is correct, we have two cases of how nibbles are packed:
Case 1: version is higher nibble (bits 4-7) and count is lower nibble (bits 0-3)
unsigned char ver = c >> 4;
unsigned char count = (c & 0x0f);
Case 2: count is higher nibble (bits 4-7) and version is lower nibble (bits 0-3)
unsigned char count = c >> 4;
unsigned char ver = (c & 0x0f);
where c is byte containing information and is declared as:
unsigned char c;
and bit numbering starts at zero for the least significant bit.
unsigned short version = (unsigned short)(data & 0x0F);
unsigned short count = (unsigned short) (data >> 4);
精彩评论