views:

177

answers:

3

Hello,

I'm very confused about behaviour of PHP's left shift function. I'm using it on two different machines (dev and hosting), and they are giving me different answers. I've tracked it down to this calculation:

(-3941404251) << 5;

On one machine I'm getting the answer -1570884448; on the other, I get 0. On both systems, PHP_INT_MAX = 2147483647. The later is a 32-bit system, and the first a 64-bit, although php is running as a 32 bit process and still gives the same answer.

I can only assume that this is a problem with 32-bit vs 64-bit, but is there any easy way to get the desired behaviour. If somebody could point me to a function or something, that would be great.

Thanks!

+1  A: 

Are the machines running the same version of PHP? (-3941404251) is already too big for a 32 bit signed value, so I suspect the "correct" result is undefined and different versions/compilations/etc giving different results wouldn't be considered a bug.

Andrew
+2  A: 

First value is correct answer for your problem. Official manual says, that you can't use bitwise operator on number greater than max_int. So try using GMP functions (For example http://www.php.net/manual/en/function.gmp-and.php) and treat number as a string.

elq
Thanks. I am considering using BC Math now (since it is better supported, as Xorlev said). Just as a note, I've noticed that this issue doesn't seem to affect shifts on positive numbers so I may just do a check for negative and throw in a minus sign after the result -- I'm sure there'll be some complications with this though. Thanks for your help.
Brendon
+1  A: 

You can use the BC Math functions to overcome the integer limitations. It's an alternative to elq's GMP function answer, and likely better supported.

Xorlev