Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 989
Ibrahim Avatar asked Dec 03 '25 23:12

Ibrahim


1 Answers

Mask to a signed int.

$c = ($a ^ $b) & 0xffffffff;
if ($c & 0x80000000)
  $c -= 0x100000000;
echo $c;
like image 196
Ignacio Vazquez-Abrams Avatar answered Dec 06 '25 14:12

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!