Search code examples
javabit-manipulation

Pack an int and 2 shorts into a long


I'm having trouble packing an int, short, short into a long.

Here's what I've got so far:

int p = 123456;
short x = -567;
short y = 789;

long l = (((long) p) << 32) | (x & 0xffff0000L) | (y & 0x0000ffffL);

int p2 = (int) (l >> 32);
short x2 = (short) (l >> 48);
short y2 = (short) l;

produces

p=123456, p2=123456
x=-567, x2=1        // bad result
y=789, y2=789

The middle value is incorrect. How can I fix this?


Solution

  • You need to shift x over: replace (x & 0xffff0000L) with ((x & 0x0000ffffL) << 16).

    Then you need to fix the shift to retrieve it: short x2 = (short) (l >> 16).