为什么<< 32在javascript中不会导致0?
作者:互联网
这是错误的:
(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,unsigned,bit-manipulation,bit-shift,integer-overflow 来源: https://codeday.me/bug/20191012/1899608.html