http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count
This is the same problem in Python: Python equivalent of C code from Bit Twiddling Hacks?
I need to use this code in PHP, independently from integer size (the above code works up to 128-bit integers, which will do fine for me). Here's what I tried:
function countSetBits($int) {
$mask = (1 << PHP_INT_SIZE*8) - 1;
$int = $int - (($int >> 1) & (int) $mask/3);
$int = ($int & ((int) $mask/15)*3) + (($int >> 2) & ((int) $mask/15)*3);
$int = ($int + ($int >> 4)) & ((int) $mask/255)*15;
return ($mask & $int * ((int) $mask/255)) >> ((int) PHP_INT_SIZE - 1) * 8;
}
The reason this doesn't work (on a 64-bit machine with 64-bit PHP - Debian Squeeze) is that PHP doesn't seem to support 64-bit unsigned integers (how to have 64 bit integer on PHP?). I'm afraid I will have to use an arbitrary-precision math library. Or is there another way?