Java does it this way (using 32-bit integers) (14 calculations)
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
For 16-bit integers (short), the method can be rewritten to :
private static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x5555);
i = (i & 0x3333) + ((i >>> 2) & 0x3333);
i = (i + (i >>> 4)) & 0x0f0f;
i = i + (i >>> 4);
i = i + (i >>> 8);
return i & 0x3f;
}
For 8-bit integers (byte), it's a bit more complicated, but the general idea is there.
You can check out this link for more info on fast bit counting functions : http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/
The fastest/easiest way for any integer, which is O(0) for the best case and O(n) for the worst case (where n is the number of bits in the value) is
static private int bitcount(int n) {
int count = 0 ;
while (n != 0) {
count++ ;
n &= (n - 1) ;
}
return count ;
}