php unsigned integers and beyond

04 Jun 2012

When you have to work with binary data and unsigned integers in PHP, the following routines my be useful. bytes2bcmath takes a binary string and turns into a bcmath compatible decimal string.



// (1>>64)-1 or 0xFFFFFFFFFFFFFFFF
$val = '18446744073709551615';
$bytes = bcmath2bytes($val); // returns 8 byte string
$dec = bytes2bcmath($bytes); // and back again


    function bytes2bcmath($bytes) {
$val = '0';
for ($i = 0; $i < strlen($bytes); $i++) {
$val = bcadd(bcmul($val, 256), ord($bytes[$i]));
}
return $val;
}

function bcmath2bytes($dec) &#123;
    $str = '';
    do &#123;
        $byte = bcmod($dec, 256);
        $str .= chr($byte);
        $dec = bcdiv($dec, 256, 0);
    &#125; while ($dec != '0');

    return strrev($str);
&#125;