How to fastest count the number of set bits in php?(如何最快地计算 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++ 实现.如何计算数量在 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?
推荐答案
您可以尝试使用二进制 AND 应用掩码,并使用 shift 逐位测试,使用将迭代 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 中设置的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何最快地计算 php 中设置的位数?
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
