Here's a faster way: repeatedly clear the rightmost set bit until becomes 0. Count how many times you clear a bit.
The trick is . This expression clears the rightmost 1 bit in . Why? When you subtract 1 from , the rightmost 1 becomes 0 and all bits to its right become 1. ANDing with the original cancels them out.
Example: . Compute . Then . The rightmost 1 is gone. This algorithm runs in time where is the number of set bits, not .