The Hamming Distance Implementation in Javascript


The Hamming Distance is the number of different symbols between two strings/numbers (equal length). It can be also considered as the number of changes required to convert from one input to another.

If the inputs are integers, we can write a quick implementation in Javascript like this:

1
2
3
4
5
6
7
8
9
const hamming_distance = (a, b) => {
    let d = 0;
    let h = a ^ b;
    while (h > 0) {
        d ++;
        h &= h - 1;
    }
    return d;
}
const hamming_distance = (a, b) => {
    let d = 0;
    let h = a ^ b;
    while (h > 0) {
        d ++;
        h &= h - 1;
    }
    return d;
}

The a ^ b calculates the XOR which is the difference in bit representation of two integers and h & (h – 1) removes the LSB (least significant bit). For example, 11100 & 11011 = 11000. 10001 & 10000 = 10000.

You can test the above JS code to compute the hamming distances between two integers in this online JS editor.

JS The Hamming Distance Implementation in Javascript algorithms bit hacks Bit Masking javascript math

NodeJs / Javascript

Hamming Weight / Hamming Distance Algorithms

Here are the posts related to Hamming Distance (XOR, The number of different bits):

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
563 words
Last Post: Introducing SteemIt Auto Claim Rewards
Next Post: SteemVBS Development - GetVotingPower, Get Post URL from Comment, Suggested Password, Effective SP, VestsToSP and more!

The Permanent URL is: The Hamming Distance Implementation in Javascript

One Response

Leave a Reply