2

In Javascript

p = 105874240;
105874240
p << 5;
-906991616

But in PHP

php > echo $p = 105874240;
105874240
php > echo $p << 5;
3387975680

I search some introduce about the different, because Javascript use signed int32. But I can't find the right solution for it, all not work for me.

Could you please tell me what's going on, and how can I get the same result of Javascript in PHP. Thank you.

Tony Gao
  • 25
  • 4
  • Take a look at this http://stackoverflow.com/questions/1908492/unsigned-integer-in-javascript you need to use the `>>>` operator to convert to 32bit unsigned int in js. – steven Feb 11 '17 at 08:55
  • I mean Javascript result is right, I want PHP get the same result, not change the Javascipt. – Tony Gao Feb 11 '17 at 08:58
  • Do you know the difference(s) between signed and unsigned integers and how to tell the OS which one to use and when? – Mjh Feb 11 '17 at 10:11

1 Answers1

2

This is how I'd do it.

function to32bits($value)
{
    $value = ($value & 0xffffffff);
    if ($value & 0x80000000) $value = -((~$value & 0xffffffff) + 1);
    return $value;
}

$p = 105874240;
echo to32bits($p << 5); // -906991616
GOTO 0
  • 42,323
  • 22
  • 125
  • 158