Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Hamming Distance for 8-bit binary Values in C Language

I write a new program that compares 2 two digit unsigned integer. Compares by hamming distances. But my algorithm doesn't work perfectly. Can yo tell me what is wrong with this code :( THANKS A LOT!!

this is my counting method;

int countHammDist(unsigned int n, unsigned int m)
{
int i=0;
unsigned int count = 0 ;
for(i=0; i<8; i++){
if( n&1 != m&1 ) {
    count++;
    }
n >>= 1;
m >>= 1;

}
return count;
}

a and b 8 bit binaries.

 PrintInBinary(a);
 PrintInBinary(b);

 printf("\n %d", countHammDist(a,b));

let me show you output;

Enter two unsigned integers (0-99): 55 64
Your choices are 55 and 64
Number A: 00110111
Number B: 01000000
Hamming distance is ; 5
like image 309
Gökhan Nas Avatar asked Nov 06 '13 23:11

Gökhan Nas


People also ask

How do you find the Hamming distance between two binary 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 Hamming distance in C?

Hamming distance is a metric for comparing two binary data strings. While comparing two binary strings of equal length, Hamming distance is the number of bit positions in which the two bits are different. The Hamming distance between two strings, a and b is denoted as d(a,b).

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

00000, 01011, 10101, 11110 For two binary strings, hamming distance is number of ones in XOR of the two strings. Hamming distance of first and second is 3, so is for first and third. Hamming distance of first and fourth is 4.

What is the Hamming distance between the binary 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.


2 Answers

Put parantheses around n&1 and m&1.

if ((n&1) != (m&1))

http://ideone.com/F7Kyzg

This is because != is before &: http://www.swansontec.com/sopc.html

like image 84
Hayri Uğur Koltuk Avatar answered Nov 15 '22 07:11

Hayri Uğur Koltuk


You need to shift m too to compare the right bits.

And you need to shift them regardless of whether the equality test passes. (move the shifts outside the inner } )

like image 29
AShelly Avatar answered Nov 15 '22 09:11

AShelly