PHP bitwise AND (&) returns negative number

梦想与她 提交于 2019-12-13 10:24:57

问题


The code:

echo (5243960811416 & 4040906070209050);

Try on http://phptester.net/ and the result (right) will be 20407554584

but on my web hosting it gives -1067281896.

There's any workaround to have 20407554584? It's a 32bit limit?

Thanks

UPDATE /w SOLUTION


回答1:


SOLUTION

After searchs and searchs I found this and I re-convert in 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;
}

usage

echo BitwiseAndLarge(5243960811416 & 4040906070209050);


来源:https://stackoverflow.com/questions/30387305/php-bitwise-and-returns-negative-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!