How does x|0 floor the number in JavaScript?

断了今生、忘了曾经 提交于 2019-11-27 05:18:18

Because, according to the ECMAScript specifications, bitwise operators operators call ToInt32 on each expression to be evaluated.

See 11.10 Binary Bitwise Operators:

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

  1. Evaluate A.

  2. Call GetValue(Result(1)).

  3. Evaluate B.

  4. Call GetValue(Result(3)).

  5. Call ToInt32(Result(2)).

  6. Call ToInt32(Result(4)).

  7. Apply the bitwise operator @ to Result(5) and Result(6). The result is a signed 32 bit integer.

  8. Return Result(7).

Bitwise operators convert their arguments to integers (see http://es5.github.com/#x9.5). Most languages I know don't support this type of conversion:

    $ python -c "1.0|0"
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unsupported operand type(s) for |: 'float' and 'int'

    $ ruby -e '1.0|0'
    -e:1:in `': undefined method `|' for 1.0:Float (NoMethodError)

    $ echo "int main(){1.0|0;}" | gcc -xc -
    : In function ‘main’:
    :1: error: invalid operands to binary | (have ‘double’ and ‘int’)

When doing a floor, although it would be possible to convert the argument to an integer, this is not what most languages would do because the original type is a floating-point number.

A better way to do it while preserving the data type is to go to exponent digits into the mantissa and zero the remaining bits.

If you're interested you can take a look at the IEEE spec for floating point numbers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!