http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallelPHP等價於Bit Twiddling Hacks的C代碼?
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
這是在Python同樣的問題:Python equivalent of C code from Bit Twiddling Hacks?
我需要使用在PHP此代碼,獨立地選自整數大小(上面的代碼工作達128位的整數,這將對我來說很好)。下面是我的嘗試:
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;
}
的原因,這並不工作(64位PHP在64位機器上 - Debian的擠壓)是PHP似乎不支持64位無符號整數( how to have 64 bit integer on PHP?)。恐怕我將不得不使用任意精度的數學庫。還是有另一種方式?
這可能是更有效的反正。在解釋型語言中,最好調用兩個本地函數,而不是使用二十個運算符。另外,試試['decbin'](http://php.net/manual/en/function.decbin.php)。 – aaz 2011-03-10 14:40:48