为什么移位 0 会截断小数点?
我最近发现了这段 JavaScript 代码:
I recently found this piece of JavaScript code:
Math.random() * 0x1000000 << 0
我知道第一部分只是生成一个介于 0 和 0x1000000 (== 16777216) 之间的随机数.
I understood that the first part was just generating a random number between 0 and 0x1000000 (== 16777216).
但第二部分似乎很奇怪.执行位移 0 有什么意义?我不认为它会做任何事情.然而,经过进一步调查,我注意到移位 0 似乎 截断了数字的小数部分.此外,它是右移还是左移,甚至是无符号右移都无关紧要.
But the second part seemed odd. What's the point of performing a bit-shift by 0? I didn't think that it would do anything. Upon further investigation, however, I noticed that the shift by 0 seemed to truncate the decimal part of the number. Furthermore, it didn't matter if it was a right shift, or a left shift, or even an unsigned right shift.
> 10.12345 << 0
10
> 10.12345 >> 0
10
> 10.12345 >>> 0
10
我在 Firefox 和 Chrome 上都进行了测试,结果是一样的.那么,这种观察的原因是什么?它只是 JavaScript 的细微差别,还是在其他语言中也存在?我以为我理解位移,但这让我很困惑.
I tested both with Firefox and Chrome, and the behavior is the same. So, what is the reason for this observation? And is it just a nuance of JavaScript, or does it occur in other languages as well? I thought I understood bit-shifting, but this has me puzzled.
推荐答案
你说得对;它用于截断值.
You're correct; it is used to truncate the value.
>>
起作用的原因是因为它只对 32 位整数进行操作,因此该值被截断.(在这种情况下也常用它来代替 Math.floor
,因为按位运算符的运算符优先级较低,因此可以避免括号混乱.)
The reason >>
works is because it operates only on 32-bit integers, so the value is truncated. (It's also commonly used in cases like these instead of Math.floor
because bitwise operators have a low operator precedence, so you can avoid a mess of parentheses.)
而且由于它只对 32 位整数进行操作,因此它也相当于在舍入后带有 0xffffffff
的掩码.所以:
And since it operates only on 32-bit integers, it's also equivalent to a mask with 0xffffffff
after rounding. So:
0x110000000 // 4563402752
0x110000000 >> 0 // 268435456
0x010000000 // 268435456
但这不是预期行为的一部分,因为 Math.random()
将返回一个介于 0 和 1 之间的值.
But that's not part of the intended behaviour since Math.random()
will return a value between 0 and 1.
此外,它与 | 做同样的事情.0
,比较常见.
Also, it does the same thing as | 0
, which is more common.
相关文章