javascript - 为什么 << 32 在 javascript 中不会导致 0?

标签 javascript bit-manipulation unsigned bit-shift integer-overflow

这是错误的:

(0xffffffff << 31 << 1) === (0xffffffff << 32)

看来应该是真的。添加>>> 0任何地方都不会改变这一点。

这是为什么?我如何才能正确编写处理 << 32 的代码? ?

最佳答案

移位运算符总是有效有一个在 0-31 范围内的右操作数。

来自 the Mozilla docs :

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.

或来自ECMAscript 5 standard :

The production ShiftExpression : ShiftExpression << AdditiveExpression is evaluated as follows:

  1. Let lref be the result of evaluating ShiftExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating AdditiveExpression.
  4. Let rval be GetValue(rref).
  5. Let lnum be ToInt32(lval).
  6. Let rnum be ToUint32(rval).
  7. Let *shiftCount be the result of masking out all but the least significant 5 bits of > rnum, that is, compute rnum & 0x1F.
  8. Return the result of left shifting lnum by shiftCount bits. The result is a signed 32-bit integer.

(对于其他移位操作符也是如此。)

我不完全清楚为什么会这样,但 Java 和 C# 对它们的 32 位整数类型的工作方式相同。 (对于 64 位整数类型,操作数在 0-63 范围内。)参见 JLS 15.19例如。

我的猜测是这在通用处理器平台上是有效的,但我没有证据证明...

关于javascript - 为什么 << 32 在 javascript 中不会导致 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288111/

相关文章:

for-loop - lisp循环遍历整数位的方法

c - 使用 unsigned int 而不是 unsigned short 改变行为

javascript - 如何将日期从 Mongoose 转换为其他格式

JavaScript:创建一个接受函数和参数的函数defineFirstArg;接受更多论据

c++ - 此代码如何计算 1 位的数量?

c++ - 有符号和无符号之间的减法,然后是除法

C - 使用 unsigned int 是否只是糟糕的编码实践?

javascript - 如何使用 vanilla JavaScript 查找 div 的宽度?

javascript - 正则表达式查找字符串是否有子字符串并以另一个子字符串结尾

c++ - 将 32 0/1 值打包到单个 32 位变量的位中的最快方法是什么?