Sub topic 16
Bitwise Operators and the Hidden 32-Bit Conversion
This chapter assumes you know how JavaScript stores numbers as 64-bit floats, what the safe integer range is, and how Math.trunc differs from Math.floor. You should also be able to read numbers written in binary (0b) and hexadecimal (0x).
Every JavaScript Number is a 64-bit floating-point value, but the bitwise operators do not work on that format. Before they run, they convert each operand to a 32-bit integer and do the work on those 32 bits. Most bitwise surprises come from this hidden conversion.
The Seven Bitwise Operators
| Operator | Name | Operand conversion | Example | Result | Column | Column |
|---|---|---|---|---|---|---|
| `a & b` | AND | Int32 | `0b1100 & 0b1010` | `8` (`0b1000`) | ||
| `a \ | b` | OR | Int32 | `0b1100 \ | 0b1010` | `14` (`0b1110`) |
| `a ^ b` | XOR | Int32 | `0b1100 ^ 0b1010` | `6` (`0b0110`) | ||
| `~a` | NOT | Int32 | `~5` | `-6` | ||
| `a << n` | Left shift | Int32, count Uint32 | `1 << 4` | `16` | ||
| `a >> n` | Sign-propagating right shift | Int32, count Uint32 | `-16 >> 2` | `-4` | ||
| `a >>> n` | Zero-fill right shift | Uint32, count Uint32 | `-16 >>> 2` | `1073741820` |
Every operator except >>> returns a signed 32-bit integer. >>> is the only one that returns an unsigned 32-bit integer, from 0 to 4294967295.
How ToInt32 Works
The specification calls this conversion ToInt32. It happens in four steps:
- Convert the operand to a Number, with the same rules as
Number(). A string like"12"becomes12, and"abc"becomesNaN. - If the result is
NaN,Infinity,-Infinity,0, or-0, the answer is0. - Otherwise, truncate toward zero, which drops the fraction the way
Math.truncdoes. - Reduce the integer modulo 2³² (4294967296). If the remainder is 2³¹ or more, subtract 2³² so it falls into the signed range −2147483648 to 2147483647.
ToUint32, which >>> uses, does the same steps but skips the subtraction in step 4.
You can watch each step happen:
console.log(7.9 | 0); // 7 (fraction dropped)
console.log(-7.9 | 0); // -7 (toward zero, not floor)
console.log(2 ** 31 | 0); // -2147483648 (wrapped into the negative range)
console.log(2 ** 32 | 0); // 0 (exactly one full wrap)
console.log(1e10 | 0); // 1410065408 (1e10 - 2 * 2**32)
console.log(NaN | 0); // 0
console.log(Infinity | 0); // 0
console.log("12" | 0); // 12 (string converted first)
console.log("abc" | 0); // 0 (NaN becomes 0)
console.log(Number.MAX_SAFE_INTEGER | 0); // -1 (low 32 bits are all ones)x | 0 changes nothing in the bits it keeps, because OR with zero leaves every bit as it is. That makes it a quick way to see what ToInt32 does to any value.
Gotcha: `| 0` and `~~` Are Not Math.trunc
Older code often uses x | 0 or ~~x (double NOT) to truncate a number. The two forms give the same result as Math.trunc only for values that fit in a signed 32-bit integer. Outside that range they wrap without any warning, and they turn NaN into 0 where Math.trunc keeps it.
const inputs = [3.7, -3.7, -0.5, 2 ** 31 + 0.5, 1e10, NaN, Infinity];
for (const x of inputs) {
console.log(x, Math.trunc(x), x | 0, ~~x);
}
// 3.7 3 3 3
// -3.7 -3 -3 -3
// -0.5 -0 0 0
// 2147483648.5 2147483648 -2147483648 -2147483648
// 10000000000 10000000000 1410065408 1410065408
// NaN NaN 0 0
// Infinity Infinity 0 0Modern engines optimize Math.trunc well, so the bitwise forms give no real speed advantage. They make sense only when 32-bit integers are what you want, for example in hash functions, checksums, or code ported from C.
Shift Counts Are Masked to Five Bits
The right operand of a shift goes through ToUint32, and then only its low 5 bits are used. That is the same as n & 31. Shifting by 32 therefore shifts by 0, not by 32.
console.log(1 << 31); // -2147483648 (the sign bit is set)
console.log(1 << 32); // 1 (32 & 31 === 0)
console.log(1 << 33); // 2 (33 & 31 === 1)
console.log(8 >> -1); // 0 (-1 becomes 31 after masking)1 << 31 is negative because bit 31 is the sign bit in a signed 32-bit integer. If you need 2³¹ as a positive number, write 2 ** 31 or (1 << 31) >>> 0.
`>>` Versus `>>>`
>> copies the sign bit into the positions that open up on the left, so negative numbers stay negative. >>> fills them with zeros and reads the result as unsigned.
console.log(-16 >> 2); // -4
console.log(-16 >>> 2); // 1073741820
console.log(-1 >>> 0); // 4294967295x >>> 0 is the standard way to read a 32-bit pattern as unsigned. You need it when you print bits, because toString on a negative number prints a minus sign rather than the two's complement bits:
console.log((-1).toString(16)); // "-1"
console.log((-1 >>> 0).toString(16)); // "ffffffff"
console.log((-6 >>> 0).toString(2)); // "11111111111111111111111111111010"
console.log((5).toString(2).padStart(8, "0")); // "00000101"NOT and Two's Complement
JavaScript stores negative 32-bit integers in two's complement, so ~x always equals -x - 1 for any value that survives ToInt32 unchanged. The only value whose NOT is 0 is -1. Older code relied on that with if (~str.indexOf(sub)), because indexOf returns -1 when nothing is found. str.includes(sub) says the same thing more clearly.
console.log(~5); // -6
console.log(~-1); // 0
console.log(~0); // -1A Practical Use: Bit Flags
Bitwise operators are a good fit for packing several on/off options into one integer. Each flag gets its own bit, and a 32-bit integer holds up to 32 flags.
const READ = 1 << 0; // 0b001
const WRITE = 1 << 1; // 0b010
const EXEC = 1 << 2; // 0b100
let perms = READ | WRITE; // set two flags
console.log((perms & WRITE) !== 0); // true: WRITE is set
console.log((perms & EXEC) !== 0); // false: EXEC is not set
perms |= EXEC; // turn EXEC on
perms &= ~WRITE; // turn WRITE off
perms ^= READ; // toggle READ (now off)
console.log(perms.toString(2)); // "100"Compare with !== 0 instead of === true, because & returns a number. If you use the flag in bit 31, perms & FLAG gives a negative number. It still works with !== 0, but it fails if you test > 0.
BigInt Has Bitwise Operators Too
The BigInt chapter covers BigInt in full. For bitwise work, note that &, |, ^, ~, <<, and >> also work on BigInt values, without any 32-bit limit and without wrapping. >>> throws a TypeError for BigInt, because a BigInt has no fixed width to fill with zeros. As with arithmetic, you cannot mix BigInt and Number in one expression.
console.log((1n << 40n) | 1n); // 1099511627777n
console.log(5n & 3n); // 1n
try {
console.log(5n | 1);
} catch (e) {
console.log(e instanceof TypeError); // true
}Decision Guide
| Goal | Use | Column |
|---|---|---|
| Drop the fraction from any number | `Math.trunc(x)` | |
| Force a value into signed 32-bit range on purpose (hashes, C ports) | `x \ | 0` |
| Read a 32-bit pattern as unsigned, or print its bits | `x >>> 0` | |
| Store up to 32 boolean options | Bit flags with `&`, `\ | `, `^`, `~` |
| Bit operations on integers wider than 32 bits | BigInt operators |
Exercise
Predict the output of each line, then explain the first two: console.log(3000000000 | 0); console.log(-0.9 | 0); console.log(1 << 35); console.log((-8 >>> 0).toString(16));
Show answer
-1294967296, 0, 8, "fffffff8". 3000000000 is at least 2³¹ (2147483648), so ToInt32 subtracts 2³² (4294967296) and gives -1294967296. -0.9 truncates toward zero to -0, and ToInt32 turns any zero into 0. The shift count 35 is masked to 35 & 31 = 3, so the result is 1 << 3 = 8. >>> 0 reads -8 as unsigned (4294967288), which is fffffff8 in hex.
Exercise
A colleague writes const seconds = (Date.now() / 1000) | 0; to get a Unix timestamp in whole seconds. Is this safe, and what would you write instead?
Show answer
It works today, because the current Unix time in seconds (about 1.8 billion) is below 2147483647. It breaks on 19 January 2038, when the value passes 2³¹ − 1 and | 0 wraps it to a negative number, the same bug as the C "Year 2038 problem." Write Math.floor(Date.now() / 1000) instead. It handles any safe integer and states the intent clearly.
Exercise
Write a function countSetBits(n) that returns how many 1 bits the 32-bit pattern of n contains, so that countSetBits(-1) returns 32 and countSetBits(5) returns 2.
Show answer
function countSetBits(n) { let x = n >>> 0; let count = 0; while (x !== 0) { count += x & 1; x >>>= 1; } return count; } Converting with >>> 0 first and shifting with >>> fills from the left with zeros, so the loop ends. A >> shift would keep copying the sign bit of a negative number, and x would never reach 0.