Nilzone-
Nilzone-

Reputation: 2786

Right shift operator - Javascript

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

Answers (1)

SheetJS
SheetJS

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:

  1. Let lref be the result of evaluating ShiftExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating AdditiveExpression.
  4. Let rval be GetValue(rref).
  5. Let lnum be ToInt32(lval). ← The number is converted to a 32 bit integer here
  6. Let rnum be ToUint32(rval).
  7. Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
  8. Return the result of performing a sign-extending right shift of lnum by shiftCount bits. The most significant bit is propagated. The result is a signed 32-bit integer.

Upvotes: 4

Related Questions