Hamming Distance Calculator
Count the positions where two equal-length strings differ — for binary codewords or plain text.
Length 7; the characters differ at indices 2, 3, 4 (0-based).
Aligned comparison — highlighted columns differ
3 columns differ.
The Hamming distance between two equal-length strings is the number of positions at which their characters differ. Compare them position by position and count the mismatches. For “karolin” and “kathrin”, the letters differ at indices 2, 3, and 4 (r/t, o/h, l/r), so the Hamming distance is 3.
What the Hamming distance measures
Named after Richard Hamming, the distance counts how many single-character edits — substitutions only — separate one string from another of the same length. Line the two strings up, walk through them one position at a time, and add one for every position where the characters disagree. It works on anything: binary codewords such as 1011101 and 1001001, DNA bases, or ordinary words. The one firm requirement is that both strings have the same length, because the metric is defined position-by-position and there is no meaningful comparison once the strings drift out of alignment.
A and B must have the same length; count every position whose characters differ.
Worked example: “karolin” vs “kathrin”
Both words have seven letters, so the comparison is well defined. Check each index in turn.
- 1 Check the lengths match. “karolin” and “kathrin” both have 7 characters, so a Hamming distance exists.
- 2 Align the strings and index from 0. k(0) a(1) r(2) o(3) l(4) i(5) n(6) against k a t h r i n.
- 3 Compare each position. Indices 0, 1, 5, and 6 match; index 2 is r vs t, index 3 is o vs h, index 4 is l vs r.
- 4 Count the mismatches. Three positions differ: indices 2, 3, and 4.
- 5 Read off the distance. The Hamming distance is 3.
Example pairs and their Hamming distance
Each pair is the same length; the distance is the count of differing positions.
| String A | String B | Differing indices | Distance |
|---|---|---|---|
| karolin | kathrin | 2, 3, 4 | 3 |
| 1011101 | 1001001 | 2, 4 | 2 |
| 1010 | 1010 | (none) | 0 |
| toned | roses | 0, 2, 4 | 3 |
Why it matters in coding theory
The Hamming distance is the backbone of error-detecting and error-correcting codes. If a transmitted codeword picks up bit errors, the received word lands some Hamming distance away from the original. The minimum Hamming distance of a code — the smallest distance between any two valid codewords — sets its power: a code with minimum distance d can detect up to d − 1 errors and correct up to ⌊(d − 1) ÷ 2⌋ of them. That is why parity checks, Hamming codes, and modern schemes are all designed to spread their valid codewords as far apart as possible. Remember the metric only applies to equal-length strings; when insertions or deletions can shift characters, the Levenshtein (edit) distance is the right tool instead.