Large hex values with PHP hexdec

As said on the hexdec manual page:

The function can now convert values
that are to big for the platforms
integer type, it will return the value
as float instead in that case.

If you want to get some kind of big integer (not float), you’ll need it stored inside a string. This might be possible using BC Math functions.

For instance, if you look in the comments of the hexdec manual page, you’ll find this note

If you adapt that function a bit, to avoid a notice, you’ll get:

function bchexdec($hex)
{
    $dec = 0;
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++) {
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
    }
    return $dec;
}

(This function has been copied from the note I linked to; and only a bit adapted by me)

And using it on your number:

$h="D5CE3E462533364B";
$f = bchexdec($h);
var_dump($f);

The output will be:

string '15406319846273791563' (length=20)

So, not the kind of big float you had ; and seems OK with what you are expecting:

Result from calc.exe =
15406319846273791563

Hope this help 😉

And, yes, user notes on the PHP documentation are sometimes a real gold mine 😉

Leave a Comment