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

2

5

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
Hygrometric answered 6/11, 2013 at 23:6 Comment(5)
don't you need to shift both n and m? Otherwise you are comparing the ith bit of n with first bit of m each time.Trapezohedron
oh, i thought that one of them is shifting other one is stays same, too much calculate today, Thanks a lot.Mylohyoid
bitcount (a^b) should do the trick. (for bitcount: see stanford bit hacks)Gallant
thanks for help but i don't want to use ^ :)Mylohyoid
In that case you could use (a|b) - (a&b) shudder. or (a|b) & ~(a&b)Gallant
T
8

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

Torray answered 6/11, 2013 at 23:50 Comment(0)
C
2

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 } )

Casual answered 6/11, 2013 at 23:7 Comment(1)
method and output editted, result is increased but not correct yet :(Mylohyoid

© 2022 - 2024 — McMap. All rights reserved.