Sub topic 16
Bitwise Operators and the Hidden 32-Bit Conversion
This chapter assumes you already know that every JavaScript Number is a 64-bit float, where the safe integer range ends, and how Math.trunc behaves. Bitwise operators work on a different representation, and that difference explains several odd results.
The working model
Bitwise operators work on individual bits, not on floats. These are the operators: &, |, ^, ~, <<, >>, and >>>. Before any of them runs, JavaScript converts each operand to a 32-bit signed integer. The spec calls this step ToInt32, and it does three things:
- It converts
NaN,Infinity, and-Infinityto0. - It truncates the fraction toward zero.
- It wraps the result modulo 2^32 into the range -2,147,483,648 to 2,147,483,647.
The operator then works on those 32 bits, and the result becomes a Number again.
Seeing the conversion
console.log(5 & 3); // 1
console.log(5 | 3); // 7
console.log(5 ^ 3); // 6
console.log(~5); // -6
console.log(7.9 | 0); // 7
console.log(-7.9 | 0); // -7
console.log(NaN | 0); // 0
console.log(Infinity | 0); // 0
console.log(2 ** 31 | 0); // -2147483648
console.log((2 ** 32 + 5) | 0); // 5
console.log(3000000000 | 0); // -1294967296
console.log(1 << 31); // -2147483648x | 0 and ~~x both work as a short "truncate to integer" idiom. Each one is ToInt32 with no other effect. They match Math.trunc only while the value fits in 32 bits.
Signed and unsigned shifts
>> keeps the sign bit, so negative numbers stay negative. >>> treats the operand as an unsigned 32-bit integer (ToUint32) and fills from the left with zeros. Its result is always between 0 and 4,294,967,295.
console.log(-16 >> 2); // -4
console.log(-16 >>> 2); // 1073741820
console.log(-1 >>> 0); // 4294967295x >>> 0 is a common way to get the unsigned 32-bit view of a value, for example when working with hash codes or color values.
Common errors
| Mistake | What goes wrong | Better choice | Column |
|---|---|---|---|
| `bigValue \ | 0` to drop decimals | Values beyond ±2^31 wrap to unrelated numbers | `Math.trunc(bigValue)` |
| `~~input` to parse user input | `NaN` silently becomes `0` | Validate with `Number.isNaN` first | |
| `1 << 32` to mean 2^32 | The shift count is taken modulo 32, so the result is `1` | `2 ** 32` | |
| Using `^` for powers | `^` is XOR: `2 ^ 3` is `1` | `2 ** 3` |
Exercise
What do 4294967297.9 | 0 and Math.trunc(4294967297.9) return, and why do they differ?
Show answer
4294967297.9 | 0 returns 1. ToInt32 truncates to 4294967297, which is 2^32 + 1, and wrapping modulo 2^32 leaves 1. Math.trunc(4294967297.9) returns 4294967297 because it only removes the fraction and never wraps.
Exercise
Why does -1 >>> 0 print 4294967295 while -1 >> 0 prints -1?
Show answer
The bits of -1 in 32-bit two's complement are all ones. >> reads them as a signed integer, which is -1. >>> reads the same bits as an unsigned integer, which is 2^32 - 1 = 4294967295.