Bitwise XOR运算符不在python中工作

时间:2022-10-23 08:08:34

I am trying to do this :

我想这样做:

print 17593028247552 ^ 909522486

打印17593028247552 ^ 909522486

The result must be 67450422(as is in javascript) but I am getting 17592253494838L

结果必须是67450422(在javascript中),但我得到17592253494838L

Please help me ! Thanks in advance :)

请帮帮我 !提前致谢 :)

2 个解决方案

#1


7  

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.

Python 2的long类型(或Python 3中的int)可以根据需要增长,但看起来你想要32位结果。

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.

您只需要屏蔽结果,这样您只能获得结果的低32位。我想,既然你在Python 2上,你也应该将它从long转换为int。

>>> int((17593028247552 ^ 909522486 ) & 0xffffffff)
67450422

#2


0  

I just used Windows calculator:

我只使用Windows计算器:

100000000000000110010001100110000000000000000  = 17593028247552d
000000000000000110110001101100011011000110110  =      909522486d
100000000000000000100000001010011011000110110  = 17592253494838d

Looks like JavaScript is wrong. It's probably narrowing to 32 bit or something before doing XOR. Python is arbitrary precision on integers.

看起来像JavaScript是错误的。在进行XOR之前,它可能会缩小到32位。 Python是整数的任意精度。

Edit: As the other answer points out, if you're still using Python 2 (don't do that!) only long is arbitrary precision; the precision of int can vary but it's usually 64 bit. In Python 3 there is only one integer type and it's always arbitrary precision.

编辑:正如另一个答案所指出的那样,如果你还在使用Python 2(不要这样做!),那么长期就是任意精度; int的精度可以变化,但通常是64位。在Python 3中,只有一个整数类型,它始终是任意精度。

#1


7  

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.

Python 2的long类型(或Python 3中的int)可以根据需要增长,但看起来你想要32位结果。

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.

您只需要屏蔽结果,这样您只能获得结果的低32位。我想,既然你在Python 2上,你也应该将它从long转换为int。

>>> int((17593028247552 ^ 909522486 ) & 0xffffffff)
67450422

#2


0  

I just used Windows calculator:

我只使用Windows计算器:

100000000000000110010001100110000000000000000  = 17593028247552d
000000000000000110110001101100011011000110110  =      909522486d
100000000000000000100000001010011011000110110  = 17592253494838d

Looks like JavaScript is wrong. It's probably narrowing to 32 bit or something before doing XOR. Python is arbitrary precision on integers.

看起来像JavaScript是错误的。在进行XOR之前,它可能会缩小到32位。 Python是整数的任意精度。

Edit: As the other answer points out, if you're still using Python 2 (don't do that!) only long is arbitrary precision; the precision of int can vary but it's usually 64 bit. In Python 3 there is only one integer type and it's always arbitrary precision.

编辑:正如另一个答案所指出的那样,如果你还在使用Python 2(不要这样做!),那么长期就是任意精度; int的精度可以变化,但通常是64位。在Python 3中,只有一个整数类型,它始终是任意精度。