本文介绍了为什么在某些情况下JavaScript中按0进行按位移位会产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是在JavaScript中进行了异常的按位操作,在某些情况下,我得到了一些奇怪的结果:

Just played around with unusual bitwise operations in JavaScript and I got some weird results in some cases:

常用案例

Usual cases

1 << 0            // returns 1, makes sense
100 << 0          // returns 100, makes sense
100 >> 0          // returns 100, definitely makes sense

但是这些,当移位0位时,全都为零

But these, when shift by 0 bits, all yield zero

9E99 << 0         // returns 0 ..... Why all bits are cleared?
9E99 >> 0         // returns 0 also  ..... All bits cleared?
Infinity >> 0     // returns 0
Infinity << 0     // returns 0
-Infinity << 0    // returns 0 .... Can't explain why
-0 << 0           // also yields 0 not -0 itself
-0 >> 0           // also resolved to 0

如果无穷大和按位移位

What if Infinity and bitwise shift

1 << Infinity     // returns 1  .. no changes
1024 << Infinity  // returns 1024 .. no changes
1024 >> Infinity  // returns 1024 .. no changes either
Infinity >> Infinity      // 0
Infinity << Infinity      // 0

上述情况对我来说没有多大意义.将整数移位零位时,值不变. 但是当您将 Infinity 移0位时,实际上会返回0 .为什么?

Those cases above don't make much sense to me. When shift an integer by zero bits, the value doesn't change. But when you shift Infinity by 0 bits, it actually returns you 0. Why?

我认为将任何数值都移位0位应该不会更改其值,不是吗?

I thought shifting any numeric value by 0 bit should not change its value, doesn't it?

此外,当将一个小的整数值移位无穷大位时,该值完全不变.但是,当您将无穷大移位任何值时,它将被0代替.

Further, when shift a small integer value by infinity bits, the value doesn't change at all. But when you shift Infinity by any values, it is replaced by 0 instead.

我真的很好奇为什么会发生这些现象?是否有任何规范或理论可以解释这些奇怪的行为?

I'm really curious why these phenomena happen? Is there any specifications or theory that explain these odd behaviors?

推荐答案

来自MDN:

JavaScript中的所有数字均为 IEEE754双精度浮点数.在应用按位运算符之前,它们已转换为32位整数.

All numbers in JavaScript are IEEE754 double precision floating point numbers. They're converted to 32 bits integers before being applied bitwise operators.

更准确地说,此过程在 ToInt32中进行了描述(在规范中):

More precisely, this process is described in ToInt32 in the spec:

如您所见,精确描述了Infinities和 -0 的转换.

As you see, the transformation of Infinities and -0 is precisely described.

这是一个二进制截断,这也解释了为什么将 9E99 更改为 0 的原因:如果您查看右边的32位,则最明显>(9E99).toString(2)(将其粘贴到控制台中,它们都是 0 ).

This is a binary truncation, which also explains why 9E99 is changed into 0: This is most obvious if you look at the 32 bits at the right of (9E99).toString(2) (paste it in your console, they're all 0).

这篇关于为什么在某些情况下JavaScript中按0进行按位移位会产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 09:23