Hamming Distance:
For example, two binary number: 1011 and 1000's HD(Hamming distance) is 2.
The 10000 and 01111's HD is 5.
Here is the code:
Can some one explain it to me?
Thanks!
short HammingDist(short x, short y)
{
short dist = 0;
char val = x^y;// what's the meaning?
while(val)
{
++dist;
val &= val - 1; // why?
}
return dist;
}
To calculate the Hamming distance, you simply count the number of bits where two same-length messages differ. An example of Hamming distance 1 is the distance between 1101 and 1001 . If you increase the distance to 2 , we can give as an example 1001 and 1010 .
The Hamming distance d(10101, 11110) is 3 because 10101 ⊕ 11110 is 01011 (three 1s).
In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
Definition 1 (Hamming distance) Given two vectors u,v ∈ Fn we define the hamming distance between u and v, d(u,v), to be the number of places where u and v differ. Thus the Hamming distance between two vectors is the number of bits we must change to change one into the other.
This instruction will give you a number with all bits that differs from x to y are set :
char val = x^y;
Example : 0b101 ^ 0b011 = 0b110
Notice that val
should have the same type of the operands (aka a short
). Here, you are downcasting a short
to a char
, loosing information.
The following is an algorithm used to count the number of bits set in a number :
short dist = 0;
while(val)
{
++dist;
val &= val - 1; // why?
}
It is known as the Brian Kernighan algorithm.
So finally, the whole code counts bits that differs, which is the hamming distance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With