Difference between ^ Operator in JS and Python

笑着哭i 提交于 2019-12-23 23:52:18

问题


I need to port some JS code which involves Math.random()*2147483648)^(new Date).getTime(). While it looks like for smaller numbers, the python function and the JS function are equivalent in function, but with large numbers like this, the values end up entirely different.

Python:

>>> 2147483647 ^ 1257628307380
1257075044427

Javascript:

> 2147483647 ^ 1257628307380
-1350373301

How can I get the Javascript value from python?


回答1:


Python has unlimited-precision integers, while Javascript is using a 32-bit integer. You can manually apply a 32-bit limit to get the result you want:

def xor32bit(a, b):
    m = (a ^ b) % (2**32)
    if m > (2**16):
        m -= 2**32
    return m



回答2:


Easiest way would be to use ctypes to get the same overflow behavior as Javascript:

>>> import ctypes
>>> ctypes.c_int(1257075044427)
c_long(-1350373301)

To get the value:

>>> ctypes.c_int(1257075044427).value
-1350373301


来源:https://stackoverflow.com/questions/1694507/difference-between-operator-in-js-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!