Skip to content

Instantly share code, notes, and snippets.

@paragonie-scott
Last active March 26, 2017 14:06
Show Gist options
  • Save paragonie-scott/89ea8ec224a3582092ad to your computer and use it in GitHub Desktop.
Save paragonie-scott/89ea8ec224a3582092ad to your computer and use it in GitHub Desktop.
Add two integers modulo 2^32 on a 32-bit system
<?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;
}
<?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 );
@paragonie-scott
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment