Java storing two ints in a long

y is getting sign-extended in the first snippet, which would overwrite x with -1 whenever y < 0.

In the second snippet, the cast to int is done before the shift, so x actually gets the value of y.

long l = (((long)x) << 32) | (y & 0xffffffffL);
int x = (int)(l >> 32);
int y = (int)l;

Leave a Comment