Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the hamming distance of two short int?

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;
}
like image 418
David Ding Avatar asked Mar 18 '14 12:03

David Ding


People also ask

How do you find the Hamming distance between two numbers?

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 .

What is the Hamming distance of bit strings 10101 and 11110?

The Hamming distance d(10101, 11110) is 3 because 10101 ⊕ 11110 is 01011 (three 1s).

What is the Hamming distance between two strings?

In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.

What is Hamming distance between two vectors?

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.


1 Answers

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.

like image 190
Kiwi Avatar answered Oct 21 '22 02:10

Kiwi