Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP bitwise OR vs Javascript bitwise OR

Javascript:

var a=209348540618090 | 0;//-1050290838

PHP:

$a= 209348540618090|0;//209348540618090
$a=(209348540618090 & 0xffffffff) | 0;  //3244676458

Why is the result of the bitwise operation in PHP different to the bitwise operation in Javascript?

like image 747
oabarca Avatar asked Jan 18 '26 07:01

oabarca


1 Answers

Bitwise operators operate on 32-bit integers in JavaScript. Here's how it converts the integer before applying the OR operator:

  1. Take 209348540618090 modulus 2^32. Result is 3244676458.
  2. Since 3244676458 is greater than 2^31 = 2147483648, substract 2^32. Result is -1050290838.
  3. Bitwise OR -1050290838 and 0, result is -1050290838.

Reference on how JS converts the number to a 32-bit integer: https://tc39.es/ecma262/multipage/abstract-operations.html#sec-toint32

On the other hand, the PHP example simple applies bitwise OR to the binary representation of the operands, which result in 3244676458.

like image 165
xuhdev Avatar answered Jan 20 '26 22:01

xuhdev