Low level bit manipulation has never been my strong point. I will appreciate some help in understanding the following use case of bitwise operators.Consider…
int age, gender, height, packed_info;
. . . // Assign values
// Pack as AAAAAAA G HHHHHHH using shifts and "or"
packed_info = (age << 8) | (gender << 7) | height;
// Unpack with shifts and masking using "and"
height = packed_info & 0x7F; // This constant is binary ...01111111
gender = (packed_info >> 7) & 1;
age = (packed_info >> 8);
I am not sure what this code is accomplishing and how? Why use the magic number 0x7F ? How is the packing and unpacking accomplished?
As the comment says, we’re going to pack the age, gender and height into 15 bits, of the format:
Let’s start with this part:
To start with, age has this format:
where each A can be 0 or 1.
<< 8moves the bits 8 places to the left, and fills in the gaps with zeroes. So you get:Similarly:
Now we want to combine these into one variable. The
|operator works by looking at each bit, and returning 1 if the bit is 1 in either of the inputs. So:If a bit is 0 in one input, then you get the bit from the other input. Looking at
(age << 8),(gender << 7)andheight, you’ll see that, if a bit is 1 for one of these, it’s 0 for the others. So:Now we want to unpack the bits. Let’s start with the height. We want to get the last 7 bits, and ignore the first 8. To do this, we use the
&operator, which returns 1 only if both of the input bits are 1. So:So:
To get the age, we can just push everything 8 places to the right, and we’re left with
0000000AAAAAAAA. Soage = (packed_info >> 8).Finally, to get the gender, we push everything 7 places to the right to get rid of the height. We then only care about the last bit: