开发者

PHP equivalent of C code from Bit Twiddling Hacks?

开发者 https://www.devze.com 2023-02-15 19:18 出处:网络
http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel v = v - ((v >> 1) & (T)~(T)0/3);// temp

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 >&开发者_StackOverflow中文版gt; 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?


For now, this is what I used:

    function countSetBits($int) {
            return substr_count(base_convert($int, 10, 2), '1');
    }


Try to use the following in your php script before 64-bit operations:

ini_set('precision', 20); 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号