- /**
- * Do a sum of 32-bit signed integers with 2's complement overflow.
- *
- * PHP has broken plus and minus operators, but the bitwise operators
- * (&, |, ^, ~, <<, >>) are all implemented as a simple wrapper around the
- * underlying C operator. The algorithm here uses a binary view of addition
- * to simulate 32-bit addition using 31-bit registers.
- */
- public static function sumWithOverflow( $a, $b ) {
- $sum = $a + $b;
- if ( is_float( $sum ) ) {
- // Use the plus operator to do a sum of the lowest 30 bits to produce a 31-bit result
- $lowA = $a & 0x3fffffff;
- $lowB = $b & 0x3fffffff;
- $sum = $lowA + $lowB;
-
- // Strip off the carry bit
- $carry = ($sum & 0x40000000) >> 30;
- $sum = $sum & 0x3fffffff;
-
- // Get the last two bits
- $highA = self::unsignedShiftRight( $a, 30 );
- $highB = self::unsignedShiftRight( $b, 30 );
-
- // Add with carry
- $highSum = $carry + $highA + $highB;
-
- // Recombine
- $sum = $sum | ( $highSum << 30 );
- }
- return $sum;
- }
-