Search code examples
javascriptpythonnumbersbitwise-or

JavaScript and Python bitwise OR operation gave different results


JS

console.log(1 | 1); // 1
console.log(1 | 0x8); // 9
console.log(1 | 0x80000000); // -2147483647

python

print (1 | 1) # 1
print (1 | 0x8) # 9
print (1 | 0x80000000) # 2147483649

Why the results in last examples are different?


Solution

  • Tha JavaScript behavior is described in MDN

    The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format, except for zero-fill right shift which results in an unsigned 32-bit integer.

    So you get negative numbers in JavaScript because it treats the value as a 32-bit signed number. The 0x80000000 bit is the sign bit.

    The qualifier at the end of the above quote points the way to get the same result as Python:

    console.log((1 | 0x80000000) >>> 0);

    >>> is the zero-fill right shift operator. Shifting by 0 bits doesn't change the value, but it gets converted to unsigned.

    Python integers have infinite precision, so they don't wrap around to negative numbers when they get to 32 bits.