0

I recently asked my first question on stack overflow (refer) For loop inside another for loop crashes in Javascript and was given a wonderful answer that seems to work (thanks Ry-) however I have been studying the code to figure out why/how it is working and am confused by the following statement "0x100000000 >>> 0"

My understanding (as learnt a few days ago) was the bitwise character >>> shifts right by pushing zeros in from the left, and the rightmost bits fall off. Therefore wouldn't " >>> 0 " have no effect to the equation?

However when I remove the bitwise the code doesn't work? Can someone explain why?

const world = document.getElementById('canvas');
const context = world.getContext('2d');

const start = performance.now();

const {width, height} = world;
const random32 = new Uint32Array(width * height);

for (let i = 0; i < random32.length; i++) {

    //THIS IS THE LINE I AM CONFUSED ABOUT
    random32[i] = Math.random() * 0x100000000 >>> 0;

}

I have tried removing ">>> 0" however the code doesn't work without it.

I have been trying to learn more about bitwise characters and Uint32Arrays but have not found anything to explain it.

  • 1
    Careful with the operator precedence there. See also: https://stackoverflow.com/q/1822350/555045 – harold Jun 26 '19 at 06:15

1 Answers1

0

JavaScript doesn't distinguish between floats and integers. However, some operations do. >>> is such an operation. Math.random() * 0x100000000 will be a float between 0 and 0x100000000. However, >>> forces it into a positive integer, since >>> only operates on integers. Then it shifts that integer by 0 digits, which indeed does nothing.

tl;dr: x >>> 0 on non-negative numbers is same as x|0 and Math.floor(x).

Amadan
  • 191,408
  • 23
  • 240
  • 301