在 Java 中获得与 Python 相同的左移值
Get same left shift value in Java as Python
具体我要取这个号:
x = 1452610545672622396
并执行
x ^= (x << 21) // 在 Python 我做 x ^= (x << 21) & 0xffffffffffffffff
并得到:12043412836254060860 // 这是我在 Python
中得到的
而不是:-6403331237455490756 // 这是我在 Java 中得到的(并且不想要)
您可以将 x 存储为 BigInteger
并对其调用 shiftLeft
,然后执行异或运算。
原因:需要61位来表示1452610545672622396,左移21会溢出一个long(64位)。
--
您不能将结果转换回 long,因为它需要 64 位,而您只能使用其中的 63 个 + 号。
(log2 12043412836254060860 = 63.3848780807)
示例代码如下:
public static void main(String[] args) {
long x = 1452610545672622396L;
BigInteger bigX = BigInteger.valueOf(x);
bigX = bigX.shiftLeft(21).xor(bigX).and(new BigInteger("ffffffffffffffff", 16));
System.out.println(bigX); // 12043412836254060860
System.out.println(bigX.longValue()); // -6403331237455490756
}
具体我要取这个号:
x = 1452610545672622396
并执行
x ^= (x << 21) // 在 Python 我做 x ^= (x << 21) & 0xffffffffffffffff
并得到:12043412836254060860 // 这是我在 Python
中得到的而不是:-6403331237455490756 // 这是我在 Java 中得到的(并且不想要)
您可以将 x 存储为 BigInteger
并对其调用 shiftLeft
,然后执行异或运算。
原因:需要61位来表示1452610545672622396,左移21会溢出一个long(64位)。
--
您不能将结果转换回 long,因为它需要 64 位,而您只能使用其中的 63 个 + 号。 (log2 12043412836254060860 = 63.3848780807)
示例代码如下:
public static void main(String[] args) {
long x = 1452610545672622396L;
BigInteger bigX = BigInteger.valueOf(x);
bigX = bigX.shiftLeft(21).xor(bigX).and(new BigInteger("ffffffffffffffff", 16));
System.out.println(bigX); // 12043412836254060860
System.out.println(bigX.longValue()); // -6403331237455490756
}