按位异或运算符在 python 中不起作用
Bitwise XOR operator not working in python
我正在尝试这样做:
打印 17593028247552 ^ 909522486
结果必须是 67450422(在 javascript 中)但我得到 17592253494838L
请帮帮我!提前致谢:)
Python 2's long
type (or int
in Python 3) can grow as large as they need to, but it looks like you want a 32 bit result.
You just need to mask the result so you only get the low 32 bits of the result. And I guess that since you're on Python 2 you should also convert it from long
to int
.
>>> int((17593028247552 ^ 909522486 ) & 0xffffffff)
67450422
我刚用过Windows计算器:
100000000000000110010001100110000000000000000 = 17593028247552d
000000000000000110110001101100011011000110110 = 909522486d
100000000000000000100000001010011011000110110 = 17592253494838d
看起来 JavaScript 是错误的。在进行 XOR 之前,它可能缩小到 32 位或其他。 Python 是整数的任意精度。
编辑:正如另一个答案所指出的,如果您仍在使用 Python 2(不要那样做!),那么 long 就是任意精度; int 的精度可能会有所不同,但通常是 64 位。在 Python 3 中只有一种整数类型,而且它总是任意精度。
我正在尝试这样做:
打印 17593028247552 ^ 909522486
结果必须是 67450422(在 javascript 中)但我得到 17592253494838L
请帮帮我!提前致谢:)
Python 2's long
type (or int
in Python 3) can grow as large as they need to, but it looks like you want a 32 bit result.
You just need to mask the result so you only get the low 32 bits of the result. And I guess that since you're on Python 2 you should also convert it from long
to int
.
>>> int((17593028247552 ^ 909522486 ) & 0xffffffff)
67450422
我刚用过Windows计算器:
100000000000000110010001100110000000000000000 = 17593028247552d
000000000000000110110001101100011011000110110 = 909522486d
100000000000000000100000001010011011000110110 = 17592253494838d
看起来 JavaScript 是错误的。在进行 XOR 之前,它可能缩小到 32 位或其他。 Python 是整数的任意精度。
编辑:正如另一个答案所指出的,如果您仍在使用 Python 2(不要那样做!),那么 long 就是任意精度; int 的精度可能会有所不同,但通常是 64 位。在 Python 3 中只有一种整数类型,而且它总是任意精度。