在 Python 中获得与 Java 相同的左移

Get the same shift left in Python as Java

具体我要取这个号:

x = 1452610545672622396

并执行

x ^= (x << 21) // In Python I do x ^= (x << 21) & 0xffffffffffffffff

我想得到:-6403331237455490756,也就是我在Java

中得到的

而不是:12043412836254060860,这是我在 Python 中得到的(这是我不想要的

编辑:在 Java 我做:

long x = 1452610545672622396;
x ^= (x << 21);

您可能会导致溢出。 Java long 是 64 位长而 python 没有大小限制。尝试使用 long 的 Long wrapper class。 Long 对象也没有限制(从技术上讲,一切都有其限制...)。

您可以像 java 使用 ctypes.c_longlong 一样使用 64 位有符号整数,请看下面的例子:

from ctypes import c_longlong as ll

x = 1452610545672622396

output = ll(x^(x<<21))

print output
print output.__class__