Bitwise Operators: A Practical Guide
AND, OR, XOR, NOT and shifts work on individual bits. Learn the operators, the masks, and the real uses in application code.
By Velloreth
The operators
| Operator | Name | Rule |
|---|---|---|
& | AND | 1 where both bits are 1 |
| | OR | 1 where either bit is 1 |
^ | XOR | 1 where the bits differ |
~ | NOT | flips every bit |
<< | left shift | move left, fill with 0 |
>> | right shift | move right, keep the sign |
>>> | unsigned right shift | move right, fill with 0 |
A truth table:
a b a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
AND
AND tests and masks.
const FLAG_READ = 0b001;
const FLAG_WRITE = 0b010;
const FLAG_EXEC = 0b100;
const perms = 0b011; // read + write
(perms & FLAG_READ) !== 0; // true
(perms & FLAG_EXEC) !== 0; // false
A mask extracts a field.
const value = 0xABCD;
const lowByte = value & 0xff; // 0xCD
const highByte = (value >> 8) & 0xff; // 0xAB
A mask clears bits.
let flags = 0b111;
flags &= ~FLAG_WRITE; // 0b101, clears the write bit
The ~FLAG_WRITE is a mask with every bit set except the write bit, so the AND clears it and leaves the rest.
A parity test: the low bit of an even number is 0.
const isEven = (n & 1) === 0;
OR
OR sets a flag.
let perms = FLAG_READ;
perms |= FLAG_WRITE; // 0b011
OR combines two masks.
const combined = FLAG_READ | FLAG_WRITE | FLAG_EXEC; // 0b111
OR rounds up to a power of two, which is a common trick in a hash table.
function nextPowerOfTwo(n) {
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}
XOR
XOR toggles a flag.
let perms = 0b011;
perms ^= FLAG_WRITE; // 0b001, the write bit is cleared
perms ^= FLAG_WRITE; // 0b011, and set again
XOR is reversible, which is why it is used in a simple cipher and a checksum.
const encoded = data ^ key;
const decoded = encoded ^ key; // the original data
XOR swaps two values without a temporary.
let a = 5, b = 3;
a ^= b; b ^= a; a ^= b;
// a is 3, b is 5
It is a curiosity rather than a practice. A temporary variable is clearer and the compiler optimises it.
XOR finds the single unpaired value in a list where every other value appears twice.
const single = nums.reduce((acc, n) => acc ^ n, 0);
NOT and shifts
NOT flips every bit.
~0b0000 // -1 in a 32-bit signed value
~0b0101 // ...11111010
A left shift multiplies by two per position.
1 << 0 // 1
1 << 1 // 2
1 << 8 // 256
A right shift divides by two per position, rounded down.
8 >> 1 // 4
9 >> 1 // 4
The signed and unsigned right shift differ on a negative number.
-8 >> 1 // -4, the sign is kept
-8 >>> 1 // 2147483644, filled with zeros
A shift past the width is undefined or wraps, depending on the language. In JavaScript a shift uses the low 5 bits of the count, so 1 << 32 is 1.
Packing values
A bitmask packs several small values into one integer.
// Pack a version: major 8 bits, minor 8 bits, patch 8 bits
const version = (major << 16) | (minor << 8) | patch;
// Unpack
const major = (version >> 16) & 0xff;
const minor = (version >> 8) & 0xff;
const patch = version & 0xff;
A colour is packed the same way.
const rgb = (r << 16) | (g << 8) | b;
const r = (rgb >> 16) & 0xff;
A permission set is a bitmask, which is how a Unix mode works.
0o755 = 111 101 101
rwx r-x r-x
Real uses
A feature flag set. One integer holds 32 flags.
A permission set. A role is a mask, and a check is an AND.
A hash function. A hash mixes the bits with shifts and XOR.
A checksum. A simple checksum XORs or adds the bytes.
A network protocol. A header packs flags and a length into a few bytes.
A graphics operation. A colour channel is extracted with a shift and a mask.
A fast modulo for a power of two.
const index = hash & (tableSize - 1); // tableSize is a power of two
Common mistakes
& where && is meant. A bitwise AND on two booleans produces a number, and it does not short-circuit.
Comparing the result of an AND to the flag. (v & FLAG) === FLAG works only when the flag is a single bit. Compare against zero.
A flag that is not a power of two. A flag of 3 is two bits, so a test is ambiguous.
Forgetting the parentheses. a & b === c parses as a & (b === c) in some languages, which is not the intent.
A shift that overflows the type. A left shift past the width discards the high bits.
A signed right shift on a negative number. Use >>> when the intent is a logical shift.
Assuming a 32-bit width. JavaScript bitwise operators convert to a 32-bit signed integer, so a value above 2^31 behaves unexpectedly.
Using a bitmask where a set is clearer. A bitmask is compact and it is not readable. Use it when the compactness matters.
A quotable summary
A bitwise operator works on the individual bits of a value: AND tests and masks, OR sets, XOR toggles, NOT flips, and a shift multiplies or divides by a power of two. A flag must be a single bit, so a set of flags is a set of powers of two, and a bitmask packs several small values into one integer. Parenthesise a bitwise expression, because the precedence is easy to get wrong, and prefer a set when the compactness does not matter.
Related reading
For the fundamentals, see binary-and-hex-explained and floating-point-precision. For the broader context, hashing-vs-encryption and unicode-and-encoding.