PHP相当于Bit Twiddling Hacks的C代码? [英] PHP equivalent of C code from Bit Twiddling Hacks?

查看:227
本文介绍了PHP相当于Bit Twiddling Hacks的C代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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相当于来自Bit Twiddling Hacks的C代码?

This is the same problem in Python: Python equivalent of C code from Bit Twiddling Hacks?

我需要在PHP中使用这个代码,独立于整数大小(上面的代码最多可以工作128位整数,这对我来说很好)。这是我试过的:

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;
}

这不起作用的原因(在64位64机器上) -bit PHP - Debian Squeeze)是PHP似乎不支持64位无符号整数(如何在PHP上使用64位整数?。我担心我将不得不使用任意精度的数学库。或者还有其他方法吗?

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');
    }

这篇关于PHP相当于Bit Twiddling Hacks的C代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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