Bitwise Operators
Working directly on the bits of a 32-bit integer -- flags, masks and fast tricks.
Syntax
a & b a | b a ^ b ~a
a << n a >> n a >>> nBitwise operators convert their operands to 32-bit signed integers and work bit by bit: & (AND), | (OR), ^ (XOR), ~ (NOT), and the shifts <<, >>, >>>.
The everyday use: flags
Pack many booleans into one number. Each bit is a flag; | sets, & tests, ^ toggles.
const READ = 1, WRITE = 2, EXEC = 4;
let perms = READ | WRITE; // 3
const canWrite = (perms & WRITE) !== 0; // trueHandy tricks
n & 1tests oddness faster than%.x ^ y ^ x === y-- XOR is its own inverse.- Unsigned shift
>>>is the only operator that yields a value above 2**31.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Store multiple boolean feature flags as bits in a single integer to reduce database columns.
- Use bitwise AND with a mask to check whether a specific permission bit is set in a permissions integer.
- Apply a bitwise OR to combine RGB channel values into a single packed color integer.
More examples
Check a permission bit with AND
Defines permission bit flags and uses & to test whether a specific bit is set in the user's permissions.
const READ = 0b001; // 1
const WRITE = 0b010; // 2
const EXEC = 0b100; // 4
const userPerms = READ | WRITE; // 3
console.log((userPerms & WRITE) !== 0); // true β has write
console.log((userPerms & EXEC) !== 0); // false β no execFast floor with bitwise OR
Uses |0 as a fast integer truncation trick; equivalent to Math.floor for positive numbers.
const x = 4.9;
console.log(x | 0); // 4 β faster integer truncation
console.log(Math.floor(x)); // 4Toggle a bit with XOR
XOR toggles a specific bit: applying the same mask twice returns to the original state.
let flags = 0b0101;
const MASK = 0b0010;
flags ^= MASK; // toggle bit 1
console.log(flags.toString(2)); // "111"
flags ^= MASK; // toggle again
console.log(flags.toString(2)); // "101"
Discussion