Calculating Hamming Distance Using XOR and Popcount
Hamming distance measures the number of bit positions in which two
binary sequences of equal length differ. In computer science and digital
communications, this metric is calculated with optimal efficiency by
chaining two fundamental operations: a bitwise Exclusive OR (XOR)
followed by a population count (popcount). The XOR
operation isolates differing bits by marking them with a binary
1, while popcount tallies these set bits to
produce the exact distance value.
The Role of the XOR Operation
The bitwise XOR operation evaluates two binary inputs bit by bit according to standard boolean logic:
- \(0 \oplus 0 = 0\) (identical bits result in 0)
- \(1 \oplus 1 = 0\) (identical bits result in 0)
- \(0 \oplus 1 = 1\) (differing bits result in 1)
- \(1 \oplus 0 = 1\) (differing bits result in 1)
When you compute \(C = A \oplus B\)
for two binary words \(A\) and \(B\), every bit position where \(A\) and \(B\) share the same value outputs
0. Conversely, every bit position where \(A\) and \(B\) differ outputs 1. The
resulting word \(C\) serves as a
bitmask indicating the exact locations of all discrepancies between the
two inputs.
The Role of Popcount
The population count function, commonly denoted as
popcount or Hamming weight, counts the total number of set
bits (1s) present in a binary word.
Because the XOR step transforms every difference into a
1 and every match into a 0, the problem of
counting differences reduces to counting the number of 1s
in the XOR product:
\[\text{Hamming Distance}(A, B) = \text{popcount}(A \oplus B)\]
Step-by-Step Example
Consider two 8-bit binary words, \(A\) and \(B\):
- Word A:
1 1 0 1 0 0 1 0 - Word B:
1 0 0 1 1 0 1 1
Apply Bitwise XOR:
1 1 0 1 0 0 1 0 (A) ^ 1 0 0 1 1 0 1 1 (B) ------------------ 0 1 0 0 1 0 0 1 (A ^ B)Apply Popcount: Count the number of
1s in01001001: \[\text{popcount}(01001001) = 3\]
The Hamming distance between word \(A\) and word \(B\) is 3.
Computational Efficiency
Modern CPU architectures (such as x86 via SSE4.2/ABM and ARM via
NEON) provide dedicated hardware instructions for both
operations—specifically XOR and POPCNT (or
VCNT). Combining these native instructions allows systems
to compute the Hamming distance in constant time, \(O(1)\), making this technique essential for
cryptography, error-correcting codes, DNA sequence alignment, and
high-dimensional vector search.