0

Explain to me why the result of the following calculation is different:

Python:

tmp = 4235635936 << 0 #4235635936

JS

let tmp = 4235635936 << 0 // -59331360

Question - how do I get the same result in python as in js ?

Mezza QU
  • 1
  • 1
  • 2
    Because those are different languages with different semantics? – AKX Sep 30 '21 at 16:15
  • Python has infinite-precision integers, JavaScript doesn't. – Barmar Sep 30 '21 at 16:16
  • 1
    Bitwise operations in JS always operate on 32 bit numbers. If a number is larger than 32 bit, it's truncated. – VLAZ Sep 30 '21 at 16:16
  • @akx I understand this, but nevertheless, how do I bring the result of execution in python to the result in js – Mezza QU Sep 30 '21 at 16:16
  • 1
    @Barmar This doesn't have to do with precision but signedness. – AKX Sep 30 '21 at 16:16
  • @VLAZ the number isn't larger than 32 bits. It is larger than 31 bits + sign bit though. :) – AKX Sep 30 '21 at 16:17
  • @AKX yes, JS bitwise operations only work on 32-bit signed two's complement binary number. Didn't think I needed to be THAT precise while looking for one of the ***many*** dupes on this exact same topic. Literally many have asked why bitwise operations differ between Python and JS. – VLAZ Sep 30 '21 at 16:19
  • @Barmar JavaScript doesn’t _by default_ — it just requires a suffix to opt in to that. `4235635936n << 0n === 4235635936n`. – Sebastian Simon Sep 30 '21 at 16:21
  • Related: [difference between JavaScript bit-wise operator code and Python bit-wise operator code](/q/41610186/4642212). – Sebastian Simon Sep 30 '21 at 16:25

2 Answers2

0

The binary representation for both numbers is the same. One is signed, the other is unsigned.

>>> struct.pack("<i", -59331360)
b'\xe0\xacv\xfc'
>>> struct.pack("<I", 4235635936)
b'\xe0\xacv\xfc'
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172
0

in JS, the bitwise operators and shift operators operate on 32-bit ints, and your example overflows the 32-bit capacity.

In Python there's no capacity limit for integers, so you get the actual value.

Yasin Br
  • 1,675
  • 1
  • 6
  • 16