How does Long.bitCount() finds the number of set bits?

Viewed 1204

I know this is the code. But I'm not able to understand what it does

 `public static int bitCount(long i){
         i = i - ((i  > > > 1) & 0x5555555555555555L);
         i = (i & 0x3333333333333333L) + ((i  > > > 2) & 0x3333333333333333L);
         i = (i + (i  > > > 4)) & 0x0f0f0f0f0f0f0f0fL;
         i = i + (i  > > > 8);
         i = i + (i  > > > 16);
         i = i + (i  > > > 32);
       return (int)i & 0x7f;
 }`
3 Answers

The algorithm is:

To count the number of 1-bits in a 2^n-bit number (in this case n = 6, but you could write this algorithm for any machine number size), split it into two halves and, using shift operations, simultaneously count the number of 1-bits in the left half and the right half, storing the result in the rightmost (least significant) bits of each half. Then combine these results by shifting the left-side to the right-side and adding.

This is a recursive algorithm---you now apply the same to both sides. The clever bit that makes it fast is that you can use shift operations which perform the algorithm on both halves simultaneously. So the algorithm is O(log(N)) where N = 2^n is the number of bits in your machine number.

So the last lines of code are doing the "recombining" for each quarter, then each half, then the whole thing.

Related