PHP 按位 AND (&) 返回负数 [英] PHP bitwise AND (&) returns negative number

查看:32
本文介绍了PHP 按位 AND (&) 返回负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

echo (5243960811416 & 4040906070209050);

尝试http://phptester.net/,结果(右)将是20407554584

但在我的虚拟主机上,它给出了 -1067281896.

but on my web hosting it gives -1067281896.

20407554584 是否有解决方法?是否有 32 位限制?

Is there a workaround to have 20407554584? Is it a 32bit limit?

推荐答案

经过多次搜索,我找到了 这个答案,我将其转换为 PHP:

After much searching, I found this answer, and I converted it to PHP:

function BitwiseAndLarge($val1, $val2) {
                
    $shift = 0; 
    $result = 0;
    $mask = ~((~0) << 30); // Gives us a bit mask like 01111..1 (30 ones)
    
    $divisor = 1 << 30; // To work with the bit mask, we need to clear bits at a time
    
    while( ($val1 != 0) && ($val2 != 0) ) {
        $rs = ($mask & $val1) & ($mask & $val2);
        $val1 = floor($val1 / $divisor); // val1 >>> 30
        $val2 = floor($val2 / $divisor); // val2 >>> 30
        
        for($i = $shift++; $i--;) {
            $rs *= $divisor; // rs << 30
        }
        
        $result += $rs;
    }
    return $result;
}

用法:

echo BitwiseAndLarge(5243960811416 & 4040906070209050);

这篇关于PHP 按位 AND (&amp;) 返回负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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