Search code examples
ccountbinarybit-manipulationhamming-distance

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

Solution

  • 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