Re:Counting set bits in an interesting way
by omegalulw on Saturday April 30, 2022 @08:56AM
(#31215691)
For those wondering how this works, n & n-1 zeros out the least significant 1. Simply by doing this repeatedly you count the number of 1s.
[ Parent
| on HN ]
Right. And the reason that zeroes out the least significant bit is because subtracting one just borrows up to it. E.g., for n = 464:
n = 464d 111010000b
n-1 = 463d 111001111b
n&(n-1) = 448d 111000000b