Bit flags
Testing whether a flag bit is set in a compact bit mask.
JS Puzzles · Const
JavaScript bitwise operators manipulate the binary representation of 32-bit integer operands. They include logical bit operations and left or right shifts, and are mainly useful for specialized low-level tasks.
JavaScript bitwise operators convert numeric operands to 32-bit integers and apply the operation to their binary representations. AND, OR, XOR, and NOT manipulate corresponding bits, while shift operators move bits left or right; the result is an ordinary JavaScript number.
a & b; a | b; a ^ b; ~a; a << b; a >> b; a >>> bEach operator produces a JavaScript number resulting from its bitwise operation.
const flags = 0b1010;
const read = 0b0010;
console.log((flags & read) !== 0); // true
console.log(flags ^ read); // 8
console.log(flags << 1); // 20
This runnable example checks a bit with AND, combines differences with XOR, and shifts bits left.
Testing whether a flag bit is set in a compact bit mask.
Combining or removing compact binary options.
Implementing specialized low-level numeric or cryptographic algorithms.
operatorsnumbersbinary representationAND (&)OR (|)XOR (^)NOT (~)LEFT SHIFT (<<)