Packing values into a single int

Posted by user303907 on Stack Overflow See other posts from Stack Overflow or by user303907
Published on 2010-12-29T01:41:07Z Indexed on 2010/12/29 1:54 UTC
Read the original article Hit count: 655

Filed under:

Hello,

Let's say I have a couple of variables like apple, orange, banana

I have 8 apples, 1 orange, 4 bananas.

Is it possible to somehow convert those values into a single integer and also revert back to their original values based on the computed integer value?

I found an example online.

int   age, gender, height;
short packed_info;
. . .
// packing
packed_info = (((age << 1) | gender) << 7) | height;
. . .
// unpacking
height = packed_info & 0x7f;
gender = (packed_info >>> 7) & 1;
age    = (packed_info >>> 8);

But it doesn't seem to work as it should when I entered random numbers.

© Stack Overflow or respective owner

Related posts about java