Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java storing two ints in a long

I want to store two ints in a long (instead of having to create a new Point object every time).

Currently, I tried this. It's not working, but I don't know what is wrong with it:

// x and y are ints long l = x; l = (l << 32) | y; 

And I'm getting the int values like so:

x = (int) l >> 32; y = (int) l & 0xffffffff; 
like image 499
LanguagesNamedAfterCofee Avatar asked Oct 07 '12 21:10

LanguagesNamedAfterCofee


2 Answers

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; 
like image 104
harold Avatar answered Sep 23 '22 19:09

harold


Here is another option which uses a bytebuffer instead of bitwise operators. Speed-wise, it is slower, about 1/5 the speed, but it is much easier to see what is happening:

long l = ByteBuffer.allocate(8).putInt(x).putInt(y).getLong(0); // ByteBuffer buffer = ByteBuffer.allocate(8).putLong(l); x = buffer.getInt(0); y = buffer.getInt(4); 
like image 22
Mingwei Samuel Avatar answered Sep 23 '22 19:09

Mingwei Samuel