Java存储两个整数

我想在一个long中存储两个int(而不是每次都要创建一个新的Point对象)。

目前,我试过这个。 它不起作用,但我不知道它有什么问题:

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

我得到的int值如下:

 x = (int) l >> 32; y = (int) l & 0xffffffff; 

y在第一个片段中进行符号扩展,只要y < 0 ,就会用-1覆盖x

在第二个片段中,转换为int的转换是在转换之前完成的,因此x实际上得到y的值。

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

这是另一个使用bytebuffer而不是按位运算符的选项。 速度方面,速度较慢,约为速度的1/5,但更容易看出发生了什么:

 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(1);