为什么移位 0 会截断小数点?

Why does a shift by 0 truncate the decimal?(为什么移位 0 会截断小数点?)
本文介绍了为什么移位 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 会截断小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)