Search code examples
javascriptbitbit-shift

Arithmetic right shift difference between do it once and do through loop


I don't know why the result of two arithmetic right are different. Can you shed light on this problem?

x=-93242
for (let i=0; i<40; i++) x >>= 1;
// now x is -1

y=-93242
y>>=40;
// now y is not -1

Solution

  • Javascript only supports bit operations for upto 32-bits. Since you are trying to shift y to the right by 40-bits it's returning y>>=8 instead. It will return -1 if you shift it to the right by 31 bits.
    Since x is being shifter right only once every iteration, it stays at -1 because -1>>=1 will always be -1.