Reputation: 2786
I'm trying to understand why i.e. Math.random()*255>>0;
will skip/remove all the decimals. Same thing happens if I write >>1
or >>2
instead of 0.
I came over another SO-post that said x >> n
operator could be looked at as x / 2^n
. That still doesn't explain why the decimals goes away.
Any help would be appreciated!
Upvotes: 0
Views: 388
Reputation: 22905
According to spec, certain numerical operations are required to convert arguments to 32 bit integers first. (http://www.ecma-international.org/ecma-262/5.1/#sec-11.7.2)
The production
ShiftExpression
:ShiftExpression
>>AdditiveExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingShiftExpression
.- Let
lval
be GetValue(lref
).- Let
rref
be the result of evaluatingAdditiveExpression
.- Let
rval
be GetValue(rref
).- Let
lnum
be ToInt32(lval
). ← The number is converted to a 32 bit integer here- Let
rnum
be ToUint32(rval
).- Let
shiftCount
be the result of masking out all but the least significant 5 bits ofrnum
, that is, computernum & 0x1F
.- Return the result of performing a sign-extending right shift of
lnum
byshiftCount
bits. The most significant bit is propagated. The result is a signed 32-bit integer.
Upvotes: 4