Search code examples
javascriptbit-shift

What does it mean that shift operators “drop any bits beyond the 5th”?


From the book “JavaScript: The Definitive Guide”:

The bitwise operators expect integer operands and behave as if those values were represented as 32-bit integers rather than 64-bit floating-point values. These operators convert their operands to numbers, if necessary, and then coerce the numeric values to 32-bit integers by dropping any fractional part and any bits beyond the 32nd. The shift operators require a right-side operand between 0 and 31. After converting this operand to an unsigned 32-bit integer, they drop any bits beyond the 5th, which yields a number in the appropriate range. Surprisingly, NaN, Infinity, and -Infinity all convert to 0 when used as operands of these bitwise operators.

I can’t understand the sentence “After converting this operand to an unsigned 32-bit integer, they drop any bits beyond the 5th, which yields a number in the appropriate range.”.

Does the fifth number have any meaning? I’m seeking for proper examples.


Solution

  • The shift operators require a right-side operand between 0 and 31.

    Meaning the right-side operand will be between 0b00000 and 0b11111 in binary form, so 5 bits.