# count bit loop

• 03-08-2011
aromash
count bit loop
Good morning,

I am given the hamming distance algorithm in C which is

Code:

```int returnDistance(int x, int y) {         unsigned dist = 0;         unsigned val = x ^ y;         while(val)         {                 ++dist;                 val &= val - 1;           }           return dist; }```
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?

Thanks.
• 03-08-2011
laserlight
Print out the value of val in the loop and observe what happens for various input. Alternatively, just observe by using a debugger.
• 03-08-2011
kmdv
Quote:

Originally Posted by aromash
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?
Thanks.

As I can see, the expression:
Code:

`val &= val - 1;`
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).