0

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!

3
  • @Phil How is this a duplicate of the link you're referring to? >> and >>> are not the same thing? Commented Nov 11, 2013 at 0:34
  • Whoops. Sorry, reading comprehension fail Commented Nov 11, 2013 at 0:42
  • possible duplicate of Why does a shift by 0 truncate the decimal? Commented Nov 11, 2013 at 0:57

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.