Wednesday, September 18, 2013

Combining 2 values into a single Byte

Doing & 0x0F and & 0xF0:

& is the bitwise AND operator. "& 0x0F" is sometimes done to replace the first 4 bits with 0s, or ignore the first(leftmost) 4 bits in a value.

0x0f = 00001111. So a bitwise & operation of 0x0f with any other bit pattern will retain only the rightmost 4 bits, clearing the left 4 bits.

If the input has a value of 01010001, after doing &0x0F, we'll get 00000001 - which is a pattern we get after clearing the left 4 bits.

Just as another example, this is a code I've used in a project:

Byte verflag = (Byte)(bIsAck & 0x0f) | ((version << 4) & 0xf0). Here I'm combining two values into a single Byte value to save space because it's being used in a packet header structure. bIsAck is a BOOL and version is a Byte whose value is very small. So both these values can be contained in a single Byte variable. 

The first nibble in the resultant variable will contain the value of version and the second nibble will contain the value of bIsAck. I can retrieve the values into separate variables at the receiving by doing a 4 bits >> while taking the value of version.

No comments:

Post a Comment