num &= num - 1;
clears the least significant bit set to num.
This algorithm counts the bit set, clearing them and increasing the counter until everything disappears.
To understand why it clears the least significant bit, you need to think about what the decrement does for the bits, and, of course, understand what the & operation does.
Subtraction in binary works is exactly the same as the process we all taught in decimal as children. You work from the right (least significant) to the left, simply by subtracting the individual digits when possible, and “borrowing” from the next digit when necessary.
When subtracting 1 from a binary number ending with a set of zeros, this “borrowing” and subtraction turn all zeros into lower positions than the rightmost ones from 1 to 1, and turn the rightmost 1 to zero (because it was borrowed).
Then, applying the & operator leaves all smaller digits zero, because they are zero in num , and sets the least significant bit of num to zero, because it is zero in num-1 .
Both of these operations leave more significant numbers unchanged.
Here's a good list of bit-hacking hacks , including this one, which is driven by Brian Kernighan .
source share