If I have the following code in JavaScript:
var index1 = (Math.random() * 6) >> 0;
var index2 = Math.floor(Math.random() * 6);
The results for index1
or index2
are anywhere between 0
and 6
.
I must be confused with my understanding of the >>
operator. I thought that by using arithmetic shift that the results for index1
would be anywhere between 1
and 6
.
I am noticing, however that I don't need to use Math.floor()
or Math.round()
for index1
if I use the >>
operator.
I know I can achieve this by adding 1
to both indexes, but I was hoping there was a better way of ensuring results are from 1
to 6
instead of adding 1
.
I'm aware that bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
UPDATE:
I saw the original usage in this CAAT tutorial on line 26 and was wondering whether that would actually return a random number between 1
and 6
and it seems it would only ever return a random number between 0
and 6
. So you would never actually see the anim1.png
fish image!
Thank you in advance for any enlightenment.