count bit loop
I am given the hamming distance algorithm in C which is
I see that this loop counts all the 1's that are found when we xor y and x, but what I'm puzzled with is how does the while loop break out? How does it know when a value is complete?
int returnDistance(int x, int y)
unsigned dist = 0;
unsigned val = x ^ y;
val &= val - 1;
Print out the value of val in the loop and observe what happens for various input. Alternatively, just observe by using a debugger.
As I can see, the expression:
Originally Posted by aromash
Removes one bit from val (sets one of them, which is 1, to 0). After a few iterations all bits will be set to 0. The loop breaks when val == 0 (all bits are 0).