在 JavaScript 中,似乎:
(4294958077 | 0) == -9219
为什么不是 4294958077 ?
这表明存在某种溢出(尽管据我所知,JavaScript 数字类型的范围是 +/- 9007199254740992,所以这本身就很奇怪。)
就算是溢出,也一定
(4294958077 | 0) == 4294958077
应该评估为 true - 但事实并非如此。
请帮忙
最佳答案
它与浮点类型或溢出无关。它返回-9219 因为标准要求这样做,因为所有二进制按位运算都必须使用有符号 32 位整数 (ECMA-262 §11.10) 来完成。
The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:
- Let lref be the result of evaluating A.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating B.
- Let rval be GetValue(rref).
- Let lnum be ToInt32(lval).
- Let rnum be ToInt32(rval).
- Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.
4294958077 转换为带符号的 32 位整数(使用 ECMA-262 §9.5 中的算法)是 -9219,而 0 仍然是 0,因此按位或将返回 -9219。
关于javascript - 为什么 JavaScript 按位或行为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9329899/