为什么在Javascript中OR 0舍入数字? [英] Why does OR 0 round numbers in Javascript?

查看:73
本文介绍了为什么在Javascript中OR 0舍入数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,根据IEEE浮点标准,Javascript中的Number类型存储了任何数字,整数或浮点数.如果是这样,那为什么要对数字与0进行按位或运算呢?

I'm under the impression that the Number type in Javascript stores any number, integer or float, according to the IEEE floating point standard. If so, then why does bitwise OR-ing a number with 0 round it down?

与其他一些位运算一起使用时,似乎将位运算应用于浮点数时,该数字首先被取整为0,然后再应用位运算(数字以二进制补码表示,而不是IEEE).这是正确的吗?

Playing around with some other bit ops, it appears that when applying bit operations to floating point numbers, the number is first rounded towards 0 and then the bit operations are applied (with the numbers in Two's complement representation rather than IEEE). Is this correct?

推荐答案

在ECMAScript 5.1中,所有按位运算都将输入转换为32位整数,并返回32位整数.关于运算符^&|部分11.10 说:

In ECMAScript 5.1, all bitwise operations will convert the input to a 32-bit integer, and return a 32-bit integer. Regarding the operators ^, & and |, section 11.10 says:

产生式A : A @ B,其中@是其中的按位运算符之一 以上产品的评估如下:

The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:

1)令lref为评估A的结果.
2)令lval为GetValue(lref).
3)令rref为评估B的结果.
4)令rval为GetValue(rref).
5)令lnum为ToInt32(lval).
6)令rnum为ToInt32(rval).
7)返回 将按位运算符@应用于lnum和rnum的结果.结果 是一个有符号的32位整数.

1) Let lref be the result of evaluating A.
2) Let lval be GetValue(lref).
3) Let rref be the result of evaluating B.
4) Let rval be GetValue(rref).
5) Let lnum be ToInt32(lval).
6) Let rnum be ToInt32(rval).
7) Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.

请注意,在两侧均应用 ToInt32 操作符被应用.

Note that ToInt32 is applied on both sides before the operator is applied.

这篇关于为什么在Javascript中OR 0舍入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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