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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.