Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does x|0 floor the number in JavaScript?

In the accepted answer on my earlier question ( What is the fastest way to generate a random integer in javascript? ), I was wondering how a number loses its decimals via the symbol | .

For example:

var x = 5.12042;
x = x|0;

How does that floor the number to 5?

Some more examples:

console.log( 104.249834 | 0 ); //104
console.log( 9.999999 | 0 );   // 9
like image 212
auroranil Avatar asked Jan 28 '12 23:01

auroranil


2 Answers

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).

like image 161
Hamish Avatar answered Oct 22 '22 05:10

Hamish


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’)

like image 45
georg Avatar answered Oct 22 '22 04:10

georg