JavaScript 和 Python 按位 OR 操作给出了不同的结果 [英] JavaScript and Python bitwise OR operation gave different results

查看:61
本文介绍了JavaScript 和 Python 按位 OR 操作给出了不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JS

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

蟒蛇

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

为什么最后几个例子的结果不同?

Why the results in last examples are different?

推荐答案

MDN

所有按位运算符的操作数都被转换为二进制补码格式的有符号 32 位整数,除了零填充右移导致无符号 32 位整数.

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 位是符号位.

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.

上面引用末尾的限定符指出了获得与 Python 相同结果的方法:

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

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

>>> 是零填充右移运算符.移位 0 位不会改变值,但会转换为无符号.

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

Python 整数具有无限精度,因此当它们达到 32 位时不会返回到负数.

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

这篇关于JavaScript 和 Python 按位 OR 操作给出了不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆