Skip to main content

How to Compute Hamming Distance: Count the Positions That Differ

A plain-English guide to Hamming distance: count differing positions in equal-length strings, XOR-and-count for binary, real uses, and how it differs from edit distance.

Published By Li Lei
#hamming-distance #bit-manipulation #error-correcting-codes #string-distance #xor

How to Compute Hamming Distance: Count the Positions That Differ

Hamming distance answers one narrow question: given two inputs of the same length, how many positions hold different symbols? That is the whole definition. You line the two sequences up, walk them position by position, and add one to a running tally every time the characters at the same index disagree. No insertions, no deletions, no clever alignment. The simplicity is exactly why it shows up everywhere from satellite links to image deduplication.

The catch is in the phrase "same length." Because Hamming compares position 1 to position 1 and position 2 to position 2, there is nothing to do with a sequence that is one symbol longer. The distance is simply undefined for mismatched lengths. If your two strings can drift in length, you want edit distance instead, which I will get to near the end.

The core rule: count positions, not characters

Here is the one rule to remember: count the positions that differ, not the number of distinct characters. A position contributes either 0 (the symbols match) or 1 (they don't), and you sum those across the whole string.

Take the classic textbook pair, karolin and kathrin. Both are seven letters long, so the comparison is legal. Walk them together:

k a r o l i n
k a t h r i n
. . x x x . .

Positions 1, 2, 6, and 7 match. Positions 3, 4, and 5 differ: r versus t, o versus h, l versus r. Three mismatches means a Hamming distance of 3. Notice that the symbol r appears in both words but at different positions, and that buys you nothing. Hamming does not care which characters are present, only whether each aligned pair agrees.

A worked binary example

Binary is where Hamming distance feels most natural, because each position is a single bit and "differ" means one bit is 0 while the other is 1.

Compare 1011 and 1001:

1 0 1 1
1 0 0 1
. . x .

Only the third bit differs, so the Hamming distance is 1. That single differing bit is exactly the kind of fault that line noise or a flipped memory cell produces, which is why a distance of 1 between an expected value and a received value is such a strong fingerprint for a single-bit error.

Push it to the extreme: 1010101 versus 0101010. Every single position disagrees, so the distance equals the length, 7. Two bit strings can be no farther apart than the number of bits they contain.

You can confirm any of these by hand in the Hamming Distance Calculator, which highlights the differing positions side by side so you never lose count on a long string.

XOR and popcount: the fast way for numbers

When your inputs are integers rather than typed-out bit strings, there is a shortcut that hardware and good code both lean on: XOR the two numbers, then count the set bits in the result. XOR outputs a 1 exactly where the two inputs differ and a 0 where they agree, so the XOR result is literally a map of the differing positions. Counting the 1s in that map (an operation called popcount, or Hamming weight) gives the distance directly.

Work it through with 42 and 13:

42 = 101010
13 = 001101
XOR  100111

The XOR result 100111 has four 1s, so the Hamming distance between 42 and 13 is 4. No alignment table, no manual walk. Most CPUs even have a single POPCNT instruction for that final count, which is why bit-distance comparisons over large datasets are so cheap.

One thing this approach handles for free: leading zeros are irrelevant. Whether you think of 1 as 1 or 00000001, the XOR with 2 produces the same two set bits. So 0001 versus 0010 and plain 1 versus 2 both give a distance of 2. Do not hand-pad your numbers expecting a different answer; the popcount already ignores the imaginary zeros out front.

Where Hamming distance actually earns its keep

The first home of Hamming distance is error-detecting and error-correcting codes, the field Richard Hamming built it for. A code whose minimum distance across all valid codewords is d can detect up to d − 1 bit errors and correct up to ⌊(d − 1)/2⌋ of them. So a minimum distance of 3 detects two flipped bits and corrects one. That single inequality is the entire reliability budget of a code, and you compute it by taking Hamming distances between codeword pairs.

It also drives similarity search through perceptual and locality-sensitive hashes. Two images run through a perceptual hash produce two 64-bit fingerprints; if the Hamming distance between those fingerprints is small, say under 10 out of 64, the images are almost certainly the same picture at a different size or compression level. The same idea powers nearest-neighbor lookups over binary embeddings, where "close" means "few differing bits."

Beyond software, Hamming distance shows up in DNA sequence comparison, counting the positions where two aligned reads of equal length differ, and in telecommunications, where it quantifies how garbled a received frame is versus what was sent.

The first time it clicked for me was debugging a flaky sensor bus. A register kept reading back slightly off, and I assumed a logic bug somewhere in my driver. I dropped the expected and received values into a binary comparison out of habit, and the distance came back as exactly 1, over and over, always at the same bit position. That was not a logic bug at all; it was a single line picking up noise. The distance number turned a vague "it's wrong sometimes" into a precise "this one bit flips," and the fix moved from my code to the hardware.

Hamming distance versus edit distance

People reach for edit distance (Levenshtein) and Hamming distance interchangeably, and they are not the same tool. Edit distance allows insertions and deletions on top of substitutions, so it can compare strings of different lengths, for example kitten and sitting at a distance of 3. Hamming allows only substitutions on aligned positions, which is precisely why it demands equal lengths.

They agree when no shift is involved. For abc versus acb, Hamming counts 2 substitutions and edit distance is also 2. But the moment one string is shifted by a character, they diverge hard: insert one symbol at the front of a string and every later position misaligns, so Hamming reports a near-maximum distance while edit distance reports 1. Use Hamming when your inputs are naturally aligned, such as two fixed-width codes or two CPU registers. Use edit distance when one side can have extra or missing characters. If you need a fuzzier, length-tolerant comparison, a string similarity checker is the better fit.

Putting it to work

The mechanics are short enough to do in your head for tiny inputs: align the two equal-length sequences, count the positions that disagree, and you have the distance. For longer strings, binary blocks, or wide integers, XOR-and-popcount keeps it fast and exact. The only real traps are feeding in two different lengths, quoting Hamming when you meant edit distance, and over-padding integers as if the leading zeros mattered.

Keep the worked example handy as a sanity check: 1011 versus 1001 is distance 1, karolin versus kathrin is distance 3, and 42 XOR 13 has four set bits for distance 4. Once those feel obvious, the error-correction bounds and the perceptual-hash thresholds stop being mysterious and start being arithmetic.


Made by Toolora · Updated 2026-06-13