-1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Oscar Zarrus
  • 790
  • 1
  • 9
  • 17
  • 1
    32-bit numbers are capped at 2^32 (4,294,967,296) for unsigned or 2^31 (2,147,483,648) for signed, to go beyond that to 64-bit you need to be using a 64-bit OS. alternatively you could attempt to split your 64-bit number into two 32-bit numbers and apply your bitwise operations on them separately. – Jonathan May 22 '15 at 02:16
  • Can I have an example please? – Oscar Zarrus May 22 '15 at 02:31
  • have a look at the [bcmath](http://php.net/manual/en/book.bc.php) class in php – Jonathan May 22 '15 at 02:43
  • Thanks a lot. So I'm on the right track. I was already seeing the BCMath class – Oscar Zarrus May 22 '15 at 02:46

1 Answers1

0

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);
halfer
  • 19,824
  • 17
  • 99
  • 186
Oscar Zarrus
  • 790
  • 1
  • 9
  • 17