Last active
March 26, 2017 14:06
-
-
Save paragonie-scott/89ea8ec224a3582092ad to your computer and use it in GitHub Desktop.
Add two integers modulo 2^32 on a 32-bit system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Since integers in 32-bit PHP 5.x are signed, exclusively, this only goes up to 2147483647 | |
*/ | |
function add_32bit($intA, $intB) | |
{ | |
if (!is_int($intA) || !is_int($intB)) { | |
return false; | |
} | |
if ($intA > 2147483647 || $intB > 2147483647) { | |
return false; | |
} | |
$sum = 0; | |
$carry = 0; | |
$rem = 0; | |
for ($i = 0; $i < 4; ++$i) { | |
$oA = $intA >> ($i * 8); | |
$oB = $intB >> ($i * 8); | |
$pA = $oA & 0xff; | |
$pB = $oB & 0xff; | |
$tmp = ($pA + $pB + $carry); | |
$rem = $tmp & 0xff; | |
$carry = ($tmp - $rem) >> 8; | |
$inc = ($rem << ($i * 8)); | |
$sum |= $inc & 0x7fffffff; | |
} | |
return $sum; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include "32bitadd.php"; | |
// Tests | |
var_dump( add_32bit(1000, 1001) ); | |
var_dump( add_32bit(1000, 2000) ); | |
var_dump( add_32bit(1, 1) ); | |
var_dump( add_32bit(10000000, 10000000) ); | |
var_dump( 2147483646, 1 ); | |
var_dump( 2147483646, 2 ); | |
var_dump( 2147483646, 3 ); | |
var_dump( 2147483646, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://3v4l.org/7AIOa