这是错误的:
(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.
The production ShiftExpression : ShiftExpression << AdditiveExpression is evaluated as follows:
- Let lref be the result of evaluating ShiftExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating AdditiveExpression.
- Let rval be GetValue(rref).
- Let lnum be ToInt32(lval).
- Let rnum be ToUint32(rval).
- Let *shiftCount be the result of masking out all but the least significant 5 bits of > rnum, that is, compute rnum & 0x1F.
- 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/