Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large hex values with PHP hexdec

Tags:

php

hex

I have some large HEX values that I want to display as regular numbers, I was using hexdec() to convert to float, and I found a function on PHP.net to convert that to decimal, but it seems to hit a ceiling, e.g.:

$h = 'D5CE3E462533364B';
$f = hexdec($h);
echo $f .' = '. Exp_to_dec($f);

Output: 1.5406319846274E+19 = 15406319846274000000

Result from calc.exe = 15406319846273791563

Is there another method to convert large hex values?

like image 333
aland Avatar asked Aug 13 '09 17:08

aland


People also ask

How to convert hex to decimal in PHP?

The hexdec() function converts a hexadecimal number to a decimal number. Tip: To convert decimal to hexadecimal, look at the dechex() function.

How to convert to hex in PHP?

The dechex() is a built-in function in PHP and is used to convert a given decimal number to an equivalent hexadecimal number. The word 'dechex' in the name of function stands for decimal to hexadecimal. The dechex() function works only with unsigned numbers.

What is bin2hex?

The bin2hex() function converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function.

What is hexadecimal code?

Hexadecimal is a numbering system with base 16. It can be used to represent large numbers with fewer digits. In this system there are 16 symbols or possible digit values from 0 to 9, followed by six alphabetic characters -- A, B, C, D, E and F.


1 Answers

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 ;-)

like image 199
Pascal MARTIN Avatar answered Oct 18 '22 22:10

Pascal MARTIN