Ad

Why Does Right Shift On Positive Number Sometimes Result In A Negative Number?

Right shifting a number in javascript sometimes results in a negative number. What is the reason behind that? Can that be mitigated?

const now = 1562143596806 // UNIX timestamp in milliseconds
console.log(now >> 8) // -4783199

Ad

Answer

Use the zero-fill right shift operator (>>>) to always get a positive result:

const now = 1562143596806 // UNIX timestamp in milliseconds
console.log(now >>> 8)

The reason for the >> operator returning the number is caused by the fact that, originally, the number is internally represented as a 64-bit floating point number:

10110101110110111000000111010000100000110

The bit shift operation will first convert the operand to a 32-bit integer. It does this by keeping only the 32 least significant bits, and discarding the rest:

10110111000000111010000100000110

Then it will shift it by the specified number of bits while maintaining the sign, i.e. shifting in 8 1 bits from the left:

11111111101101110000001110100001

Converting back to decimal, this yields:

-4783199
Ad
source: stackoverflow.com
Ad