【问题标题】:PHP equivalent of C code from Bit Twiddling Hacks?Bit Twiddling Hacks 中的 C 代码的 PHP 等价物?
【发布时间】:2011-03-07 13:02:40
【问题描述】:

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

这在 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 - Debian Squeeze 的 64 位机器上)是 PHP 似乎不支持 64 位无符号整数 (how to have 64 bit integer on PHP?)。恐怕我将不得不使用任意精度的数学库。还是有别的办法?

【问题讨论】:

    标签: php integer int 32bit-64bit bitcount


    【解决方案1】:

    目前,这是我使用的:

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

    【讨论】:

    • 这可能更有效。在解释型语言中,调用两个本机函数比使用两打运算符要好。另外,试试decbin
    【解决方案2】:

    在 64 位操作之前尝试在您的 php 脚本中使用以下内容:

    ini_set('precision', 20); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 2012-06-28
      相关资源
      最近更新 更多