I get an unexpected result when I add two negative numbers in PHP on
SPARC/Solaris 8. The same program works fine on Intel/Linux. I'm using
PHP 4.3.1 on both systems.
Here is my program, test.php.
<?php
$a = 0x81234567;
$b = 0xF0000002;
printx($a, $b);
printx($a, intval($b));
printx(intval($a), $b);
printx(intval($a), intval($b));
function printx($a, $b) {
$c = $a + $b;
printf("%08X (%u) %7s + %7s = %7s\n", $c, $c,
gettype($a), gettype($b), gettype($c));
}
?>
I run it from the shell prompt like this:
php -f test.php
Output on Intel/Linux, PHP 4.3.1
71234569 (1898136937) double + double = double
71234569 (1898136937) double + integer = double
71234569 (1898136937) integer + double = double
71234569 (1898136937) integer + integer = double
This is the answer that I expect. I am adding two 32-bit integers, and the
value overflows.
Here is what happens when I run it on
SPARC/Solaris 8, PHP 4.3.1
FFFFFFFF (4294967295) double + double = double
71234569 (1898136937) double + integer = double
71234569 (1898136937) integer + double = double
80000000 (2147483648) integer + integer = double
When both arguments are negative doubles or both are
negative integers, then it gives the wrong answer.
What is causing this, and how do I avoid this strange behavior?