javascriptbinary

Right shift operator ( >> ) can change number sign


We can read about Right shift operator >> on MDN

... the sign of the resulting number is the same as the sign of the first operand.

However, 3332508426 >> 24 === -58 in my Chrome 127.0.6533.120.

How that could be explained?

By the way, 3332508426 is decimal representation of IP 198.162.11.10.


Solution

  • MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift#description

    The >> operator is overloaded for two types of operands: number and BigInt. For numbers, the operator returns a 32-bit integer.

    As 3332508426 is already a 32-bit integer, it uses that value. However, 32-bit numbers are signed and the 32-bit binary representation of your number's left-most bit is a 1, so is a negative value.

    9 (base 10): 00000000000000000000000000001001 (base 2)
    -9 (base 10): 11111111111111111111111111110111 (base 2)

    One solution is to convert your number to BigInt first, then convert back, ie:

    let result = Number(BigInt(3332508426) >> BigInt(24));
    
    console.log(result);
    console.log(Number((BigInt(3332508426) >> BigInt(16)) % BigInt(1<<8)))
    console.log(Number((BigInt(3332508426) >> BigInt(8)) % BigInt(1<<8)))
    console.log(Number(BigInt(3332508426) % BigInt(1<<8)))