Ibrahim
Ibrahim

Reputation: 6088

PHP Bitwise XOR vs. JavaScript Bitwise XOR

I'm trying to find a way to make PHP Bitwise XOR results match the results of JavaScript Bitwise XOR. I came across different questions of this issue, and all without answers. Here are a few of them:

Javascript & PHP Xor equivalent

php bitwise XOR and js bitwise XOR producing different results

JS bitwise XOR operator acts differently from PHP’s counterpart. How to get the same result as PHP returns?

I know that PHP is using 64 bit compared to 32 bit JavaScript, but my question is, is there any manual way to count similar results? How can we make PHP get similar results as JS?

If the numbers are short, the results will always be the same in JS and PHP, However, if the numbers are long, the issue happens. Example:

var a = 234324234232;
var b = 221312312232;
console.log(a^b);

JS Output:

166587472

PHP Code:

$a = 234324234232;
$b = 221312312232;
echo $a^$b;

PHP Output:

21641423952

Sometimes JavaScript gives negative results:

var a = 202338273;
var b = 523511134400;
console.log(a^b);

JS Output

-272722143

PHP Code:

$a = 202338273;
$b = 523511134400;
echo $a^$b;

PHP Output:

523713287969

Upvotes: 3

Views: 556

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Mask to a signed int.

$c = ($a ^ $b) & 0xffffffff;
if ($c & 0x80000000)
  $c -= 0x100000000;
echo $c;

Upvotes: 7

Related Questions