What is Hamming Distance?#

Hamming Distance is the number of differing characters between two strings of equal lengths.

Example:

  • "Apple" and "Apolo": 2 characters
  • "Cat" and "Kat": 1 character
  • "Dog" and "Dog": 0 characters

The following is a JavaScript implementation of calculating the Hamming Distance between two strings.

Run
Clear

Hamming Distance between integers#

What is the Hamming Distance between 0 and 1? 1 and 9? Are they both 1? That can't be so, right?

Hamming Distance between integers is calculated at the bit level.

Here is a JavaScript implementation for calculating the Hamming Distance between two integers.

Run
Clear

The above implemenation can be further optimized by the use of bitwise operators ^ (Bitwise XOR), & (Bitwise AND) and >> (Sign-propagating right shift).

This implementation is significantly faster than the first one, since it works at the bit level and avoids string operations.

Run
Clear

In some domains, like Cryptography, it may be required to calculate the bit-level Hamming Distance between two strings. It is accomplished by converted the strings to their respective numeric ASCII codes and then running the integral Hamming Distance calculation on them.

Run
Clear

Looking for a handy online Hamming Distance calculator? There is one at /tools/calculators/hamming-distance.html.

Summary#

Hamming Distance is the number of differing characters between two strings of equal lengths or the number of differing bits between two numbers.

References#

  1. https://en.wikipedia.org/wiki/Hamming_distance
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
Tweet this | Share on LinkedIn |