Han*_*etz 4 java math bit-manipulation
我将无符号64位数的位模式存储在long变量中,并希望计算无符号范围内两个数字之间的距离.因为Java解释long为二进制补码有符号整数,所以我不能这样做a - b,如下例所示:
// on the unsigned range, these numbers would be adjacent
long a = 0x7fffffffffffffffL;
long b = 0x8000000000000000L;
// but as two's complement (or any representation that
// stores the sign in the first bit), they aren't
assert b - a == 1;
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
从Java 8开始,无符号整数的比较可以通过Long.compareUnsigned(x, y)long完成。
以下是 Java 7 及更早版本的简单向后移植:
public static int compareUnsigned(long x, long y) {
return Long.compare(x + Long.MIN_VALUE, y + Long.MIN_VALUE);
}
Run Code Online (Sandbox Code Playgroud)
如果您正在处理加法和减法,那么使用有符号或无符号类型并不重要,只要参数都是有符号的或都是无符号的即可。如果需要比较a和b,请将ab与0进行比较。