Hamming Distance Calculator
Find the Hamming distance between two equal-length inputs — binary codewords, text strings, or numeric vectors — as the count of positions that differ. See the normalised Hamming loss, the similarity, and exactly which positions mismatch. Runs entirely in your browser, no signup.
How it works
The Hamming distance between two sequences A and B of equal length n is the number of positions at which their symbols differ. It was introduced by Richard Hamming in his 1950 paper on error-detecting and error-correcting codes, and it is one of the building blocks of coding theory: a block code whose codewords are all at least a Hamming distance d apart can detect up to d − 1 errors and correct up to ⌊(d − 1) / 2⌋.
- Parse each input into a list of symbols. Binary mode keeps each 0/1 character (and rejects anything else); text mode keeps each Unicode character, optionally lower-cased; vector mode splits on a comma or space and parses each element as a number, so 2 and 2.0 compare equal.
- Length guard. If the two inputs parse to different lengths, the distance is undefined, so the tool stops and shows an error rather than padding the shorter one.
- Count the mismatches with the core formula, where [A_i ≠ B_i] is 1 when the symbols at position i differ and 0 otherwise:
d_H(A, B) = Σ [ A_i ≠ B_i ] for i = 0 … n−1
- Normalise. The normalised Hamming distance, or Hamming loss, is d_H / n— the fraction of positions that differ, between 0 and 1. This matches scikit-learn's hamming_loss and SciPy's distance.hamming.
- Similarity is 1 − d_H / n, shown as a percentage — the share of positions that agree. When both inputs are empty the loss is defined as 0 and similarity as 100%, avoiding a division by zero.
The integer distance is exact with no rounding; only the normalised value and similarity are shown to a fixed number of decimals for display. Every result is independently cross-checked against a second, reduce-based implementation of the same count — if the two ever disagreed, the badge in the tool would flag it.
Cost and limits
The comparison is a single left-to-right pass, so the work grows linearly with the length: O(n) time and O(1) extra space beyond the parsed inputs. That is what separates it from edit distance, which fills an m × n dynamic-programming table and costs O(m·n). Inputs here are capped at 5,000 raw characters per field, and the position-by-position alignment view collapses to a summary beyond 400 positions — the distance, the loss, and the list of differing indices stay exact either way; only the visual grid is trimmed, which keeps layout shift at zero on long inputs.
The binary special case: XOR and popcount
When both inputs are bit strings, the mismatch indicator [A_i ≠ B_i] is just the XOR of the two bits. So the Hamming distance of two binary words equals the population count (number of set bits) of their XOR: d_H(A, B) = popcount(A ⊕ B). That identity is why the metric is cheap enough to run inside hardware error checks and nearest-neighbour search over binary hashes. It also gives you a clean way to compare two integers: convert both to binary at the same bit width — the number base converter will pad and show the working — then count the differing bits. Padding matters: 9 is 1001 and 14 is 1110, both four bits wide, and their XOR 0111 has three set bits, so the distance is 3.
Why it counts as a proper metric
Over the set of length-nsequences, Hamming distance satisfies all four metric axioms, which is what lets it be used as a distance in clustering, nearest-neighbour search, and code design rather than as a mere score. It is never negative, because it is a count. It is zero exactly when the two inputs are identical, since a zero count means no position disagreed. It is symmetric, because “position idiffers” does not depend on which input you read first. And it obeys the triangle inequality: if A and C differ at some position, then B must differ from at least one of them there, so d(A, C) ≤ d(A, B) + d(B, C). The normalised loss inherits all four, since dividing every distance by the same fixed n preserves them.
Edge cases this tool defines
- Both inputs empty. n = 0, so the raw distance is 0 and the loss is defined as 0 (not 0/0), with similarity 100%. Two empty sequences are identical.
- Every position differs. 0000 vs 1111 gives d = 4, loss = 1, similarity 0%. The loss can never exceed 1 — that is the ceiling of the metric.
- Numeric equality, not string equality. In vector mode 2 and 2.0 are the same element, because the elements are parsed to numbers before comparison. In text mode they are two different characters and would count as a mismatch.
- Case folding. Text mode is case-sensitive by default, so A and a differ. Turn case-sensitivity off and both inputs are lower-cased before the pass, which usually lowers the distance and never raises it.
- Unequal lengths. The distance is undefined, so the tool errors rather than padding or truncating. Silently padding would invent a number that no textbook definition supports.
Hamming distance vs other string metrics
Picking the wrong metric is the usual reason a similarity number looks wrong. Hamming is positional and length-locked; the alternatives relax one or both of those constraints, and each answers a different question.
| Metric | Allows | Equal length? | Use it when |
|---|---|---|---|
| Hamming | Substitutions only | Required | Fixed-width codewords, bit strings, image or perceptual hashes, one-hot and multi-label vectors |
| Levenshtein | Insert, delete, substitute | Not required | Free-form text, typo tolerance, fuzzy name and address matching |
| Jaccard | Set membership (order ignored) | Not required | Tag sets, shingled documents, deduplication where position is noise |
| Cosine | Angle between weighted vectors | Same dimension | Embeddings and TF-IDF vectors where magnitude should not matter |
On equal-length inputs Hamming distance is always greater than or equal to Levenshtein distance, because Levenshtein is allowed every substitution Hamming uses plus two extra operations. The gap can be dramatic: shifting a string by one character, as in abcdef vs bcdefa, gives a Hamming distance of 6 — every position mismatches — but a Levenshtein distance of only 2, one deletion and one insertion. If your inputs are misaligned rather than corrupted, reach for the Levenshtein distance calculator instead, and use the text diff checker when you want to see the changes rather than score them.
Where Hamming distance is used
The metric shows up wherever data is stored or transmitted at a fixed width and you need to know how far a received value drifted from an expected one.
- Error-detecting and error-correcting codes. The minimum distance between any two codewords sets the guarantee: detect up to d − 1 errors, correct up to ⌊(d − 1) / 2⌋. A single parity bit gives d = 2 — one error detected, none corrected. The (7,4) Hamming code gives d = 3, so it corrects any single-bit error in a seven-bit block.
- The avalanche effect in hashing. A well-behaved cryptographic hash should change roughly half its output bits when a single input bit flips, so the Hamming distance between two digests of near-identical inputs should sit near n/2 — a normalised loss around 0.5. Generate two digests with the hash generator, convert them to bits, and the distance is a quick sanity check.
- Perceptual and image hashing.pHash and dHash reduce an image to a fixed 64-bit fingerprint; near-duplicates are then found by Hamming distance, with a threshold of about 10 bits out of 64 commonly used as the “same image” cutoff.
- Multi-label classification. Hamming loss is a standard metric for multi-label models — the fraction of label slots predicted wrongly across all labels, which is what sklearn.metrics.hamming_loss returns. For single-label problems the equivalent breakdown lives in the confusion matrix calculator.
- Genetics and telecommunications. Aligned DNA sequences of equal length are compared position by position to count point mutations, and DTMF, barcode, and RFID symbol sets are designed with a minimum distance so that a single misread symbol cannot become a different valid symbol.
Worked examples
Every example above was computed by hand first, then checked against the calculator and against a second independent implementation in lib/data/hamming-distance-calculator.ts. Example three is the value quoted in Hamming's original 1950 paper, and example two is the textbook karolin/kathrin pair used in most references.
Frequently asked questions
Sources & references
- Hamming, R. W. (1950) — Error detecting and error correcting codes (Bell System Technical Journal 29:147–160)
- scikit-learn — metrics.hamming_loss (normalised Hamming distance / Hamming loss)
- SciPy — scipy.spatial.distance.hamming reference
The definition, formula, and worked examples on this page were last cross-checked against these sources on 2026-06-10. Every distance is deterministic and verified against an independent second implementation on each calculation.
Related tools
Comments & feedback
Spotted a bug or want an improvement? Tell us — our team reviews every comment, and good ideas get built. Comments are public and anonymous.
Found a bug, edge case, or want to suggest an improvement?
Email me at [email protected] — most fixes ship within 24 hours.