TAGS :Viewed: 13 - Published at: a few seconds ago

[ PHP: why would dechex fail even with small number? ]

I'm having trouble converting a binary string to a hexadecimal string using bindec and dechex functions. In my research I have discovered that either PHP in general or dechex specifically has an integer size limitation of 319259235818. However, my code fails even the maximum possible integer in my application is an order of magnitude smaller

$bin = "11111111111111111111111111111111111";
var_dump($bin); //'11111111111111111111111111111111111' (length=35)

$dec = bindec($bin);
var_dump($dec); // float 34359738367

$hex = dechex($dec);
var_dump($hex); // 'ffffffff' (length=8) (binaryhexconverter.com shows 7FFFFFFFF (length 9) as the result)

$dec2 = hexdec($hex);
var_dump($dec2); //float 4294967295

$bin2 = decbin(hexdec($hex));
var_dump($bin2); //'11111111111111111111111111111111' (length=32)

What is going on?

Answer 1

It's clearly said in the documentation:

The largest number that can be converted is PHP_INT_MAX * 2 + 1 (or -1): on 32-bit platforms, this will be 4294967295 in decimal, which results in dechex() returning ffffffff.

And it's relatively clear that you're working with 32-bit platform, as bindec() produced a float, not integer in your case:

The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.

The catch is, while bindec indeed is 'smart enough' to make such a conversion, dechex won't do that - it only works with integer values.