PHP bitwise AND (&) returns negative number

2019-09-20 12: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);