Computing Library › Number Systems & Information
Number Systems & Information

Bitwise Operations

Bitwise operations apply logic gates to each bit of an integer independently and in parallel.

The core operators

AND, OR, XOR, and NOT act on corresponding bits of their operands. AND yields 1 only where both bits are 1; OR where at least one is; XOR where exactly one is; NOT flips every bit.

Truth of XOR

Kronos motion — parallel

XOR is especially useful: it is its own inverse, so applying the same value twice restores the original. This underlies simple swaps, parity, and stream cipher constructions.

Bit tricks

Why they are fast

Each bitwise operation processes all bits of a word at once in a single machine instruction. This parallelism makes them the building blocks of masks, flags, hashing, and low-level graphics and cryptography.

Logical versus bitwise

Bitwise operators work per bit and return an integer; logical operators (and, or, not) work on truth values and short-circuit. Confusing the two is a common bug, since & and && behave very differently.

ABANDORXOR
00000
01011
10011
11110
python
print(0b1100 & 0b1010)  # 8  (1000)
print(0b1100 | 0b1010)  # 14 (1110)
print(0b1100 ^ 0b1010)  # 6  (0110)