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
为什么最后一个例子的结果不同?
最佳答案
MDN 中描述了 JavaScript 行为。
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.
因此,在 JavaScript 中您会得到负数,因为它将该值视为 32 位有符号数。 0x80000000
位是符号位。
上面引用末尾的限定符指出了获得与 Python 相同结果的方法:
console.log((1 | 0x80000000) >>> 0);
>>>
是零填充右移运算符。移动 0 位不会改变值,但会转换为无符号。
Python 整数具有无限精度,因此当它们达到 32 位时不会环绕为负数。
关于JavaScript 和 Python 按位或运算给出了不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60387008/