Just played around with unusual bitwise operations in JavaScript and I got some weird results in some cases:
Usual cases
1 << 0 // returns 1, makes sense
100 << 0 // returns 100, makes sense
100 >> 0 // returns 100, definitely makes sense
But these, when shift by 0 bits, all yield zero
9E99 << 0 // returns 0 ..... Why all bits are cleared?
9E99 >> 0 // returns 0 also ..... All bits cleared?
Infinity >> 0 // returns 0
Infinity << 0 // returns 0
-Infinity << 0 // returns 0 .... Can't explain why
-0 << 0 // also yields 0 not -0 itself
-0 >> 0 // also resolved to 0
What if Infinity and bitwise shift
1 << Infinity // returns 1 .. no changes
1024 << Infinity // returns 1024 .. no changes
1024 >> Infinity // returns 1024 .. no changes either
Infinity >> Infinity // 0
Infinity << Infinity // 0
Those cases above don't make much sense to me. When shift an integer by zero bits, the value doesn't change. But when you shift Infinity
by 0 bits, it actually returns you 0. Why?
I thought shifting any numeric value by 0 bit should not change its value, doesn't it?
Further, when shift a small integer value by infinity bits, the value doesn't change at all. But when you shift Infinity by any values, it is replaced by 0 instead.
I'm really curious why these phenomena happen? Is there any specifications or theory that explain these odd behaviors?