java Java将两个整数存储在一个long中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12772939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:08:49  来源:igfitidea点击:

Java storing two ints in a long

javabit-manipulationprimitive

提问by LanguagesNamedAfterCofee

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

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

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:

我得到这样的 int 值:

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

回答by harold

yis getting sign-extended in the first snippet, which would overwrite xwith -1whenever y < 0.

y越来越符号扩展的第一个片段,它会覆盖x-1y < 0

In the second snippet, the cast to intis done before the shift, so xactually gets the value of y.

在第二个代码段中,转换int为在移位之前完成,因此x实际上获取了 的值y

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

回答by Mingwei Samuel

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:

这是另一个使用字节缓冲区而不是按位运算符的选项。速度方面,它更慢,大约是速度的 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);