Search code examples
phpbit-manipulation32-bit

PHP bitwise AND (&) returns negative number


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.

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


Solution

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

    Usage:

    echo BitwiseAndLarge(5243960811416 & 4040906070209050);