use of the bitwise operators to pack multiple values in one int

Viewed 31317

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?

Source

7 Answers

Same requirement I have faced many times. It is very easy with the help of Bitwise AND operator. Just qualify your values with increasing powers of two(2). To store multiple values, ADD their relative number ( power of 2 ) and get the SUM. This SUM will consolidate your selected values. HOW ?

Just do Bitwise AND with every value and it will give zero (0) for values which were not selected and non-zero for which are selected.

Here is the explanation:

1) Values ( YES, NO, MAYBE )

2) Assignment to power of two(2)

YES   =    2^0    =    1    =    00000001
NO    =    2^1    =    2    = 00000010
MAYBE =    2^2    =    4    = 00000100

3) I choose YES and MAYBE hence SUM:

SUM    =    1    +    4    =    5

SUM    =    00000001    +    00000100    =    00000101 

This value will store both YES as well as MAYBE. HOW?

1    &    5    =    1    ( non zero )

2    &    5    =    0    ( zero )

4    &    5    =    4    ( non zero )

Hence SUM consists of

1    =    2^0    =    YES
4    =    2^2    =    MAYBE.

For more detailed explanation and implementation visit my blog

Related