Lan*_*fee 30 java primitive bit-manipulation
我希望在一个long中存储两个int(而不是Point每次都要创建一个新对象).
目前,我试过这个.它不起作用,但我不知道它有什么问题:
// x and y are ints
long l = x;
l = (l << 32) | y;
Run Code Online (Sandbox Code Playgroud)
而我得到的int值如下:
x = (int) l >> 32;
y = (int) l & 0xffffffff;
Run Code Online (Sandbox Code Playgroud)
har*_*old 54
y越来越符号扩展的第一个片段,它会覆盖x与-1时y < 0.
在第二个片段中,强制转换int是在转换之前完成的,因此x实际得到的值为y.
long l = (((long)x) << 32) | (y & 0xffffffffL);
int x = (int)(l >> 32);
int y = (int)l;
Run Code Online (Sandbox Code Playgroud)
Min*_*uel 11
这是另一个使用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(4);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9666 次 |
| 最近记录: |