如何最快的设置位计数在PHP中的号码吗? [英] How to fastest count the number of set bits in php?

查看:142
本文介绍了如何最快的设置位计数在PHP中的号码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想找到一些速度最快的设置位计数功能在PHP。

I just want to find some fastest set bits count function in the php.

例如,0010101 => 3,00011110 => 4

For example, 0010101 => 3, 00011110 => 4

我看到有好的算法,可以在C ++中实现。 <一href="http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer">How来计算一个32位整数集位数?

I saw there is good Algorithm that can be implemented in c++. How to count the number of set bits in a 32-bit integer?

有没有PHP的内置函数或最快的用户自定义功能?

Is there any php built-in function or fastest user-defined function?

推荐答案

您可以尝试敷个面膜用的二进制文件,并用转向考位一个接一个,使用一个循环,将重复32次。

You can try to apply a mask with a binary AND, and use shift to test bit one by one, using a loop that will iterate 32 times.

function getBitCount($value) {

    $count = 0;
    while($value)
    {
        $count += ($value & 1);
        $value = $value >> 1;
    }

    return $count;
}

您还可以轻松地把你的函数到PHP风格

You can also easily put your function into PHP style

function NumberOfSetBits($v)
{
    $c = $v - (($v >> 1) & 0x55555555);
    $c = (($c >> 2) & 0x33333333) + ($c & 0x33333333);
    $c = (($c >> 4) + $c) & 0x0F0F0F0F;
    $c = (($c >> 8) + $c) & 0x00FF00FF;
    $c = (($c >> 16) + $c) & 0x0000FFFF;
    return $c;
}

这篇关于如何最快的设置位计数在PHP中的号码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆