为什么0乘以截断小数? [英] Why does a shift by 0 truncate the decimal?

查看:144
本文介绍了为什么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.

这篇关于为什么0乘以截断小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆