I recently found this piece of JavaScript code:
Math.random() * 0x1000000 << 0
I understood that the first part was just generating a random number between 0 and 0x1000000 (== 16777216).
But the second part seemed odd. What’s the point of performing a bit-shift by 0? I didn’t think that it would do anything. Upon further investigation, however, I noticed that the shift by 0 seemed to truncate the decimal part of the number. Furthermore, it didn’t matter if it was a right shift, or a left shift, or even an unsigned right shift.
> 10.12345 << 0
10
> 10.12345 >> 0
10
> 10.12345 >>> 0
10
I tested both with Firefox and Chrome, and the behavior is the same. So, what is the reason for this observation? And is it just a nuance of JavaScript, or does it occur in other languages as well? I thought I understood bit-shifting, but this has me puzzled.
You’re correct; it is used to truncate the value.
The reason
>>works is because it operates only on 32-bit integers, so the value is truncated. (It’s also commonly used in cases like these instead ofMath.floorbecause bitwise operators have a low operator precedence, so you can avoid a mess of parentheses.)And since it operates only on 32-bit integers, it’s also equivalent to a mask with
0xffffffffafter rounding. So:But that’s not part of the intended behaviour since
Math.random()will return a value between 0 and 1.Also, it does the same thing as
| 0, which is more common.