2

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?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
antimatter15
  • 1,436
  • 1
  • 12
  • 18

2 Answers2

7

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
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • Better use `1 << 32` or directly `4294967296` instead of `2**32`. – Gumbo Nov 07 '09 at 22:00
  • Using 4294967296 would be silly—it kills readability. 2**32 is not absurdly expensive and it probably constant-folded. 1<<32 makes easily as much sense. – Mike Graham Nov 07 '09 at 22:22
  • I just checked, and Python 3.1 constant-folds `2**16` and `2**32`. – u0b34a0f6ae Nov 08 '09 at 09:56
  • Yes, it seems this was introduced in Python 2.5. 2.3 and 2.4 compute the value in bytecode, but 2.5 computes it in the compiler and the bytecode simply loads the constant value. – Ned Batchelder Nov 08 '09 at 13:12
4

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
mthurlin
  • 26,247
  • 4
  • 39
  • 46