3
votes

I'm trying to convert a 64 bit hexadecimal number to a float in PHP.

40F82C719999999A

If I run that in the IEEE-754 Floating-Point Conversion page at http://babbage.cs.qc.cuny.edu/IEEE-754.old/64bit.html it converts to:

99015.100000000000

Which is the number I'm looking for. But I can't get to this number in PHP. I've tried using various combinations of pack() and unpack() but I'm not anywhere close. :(

2
Are you trying to get a float or double representation? In other words, are you running a 32 ot 64 bit version of PHP?Flosculus
Can you provide the code that you are using?James
@flosculus If PHP_INT_SIZE is to be trusted for such things I'm running a 64 Bit PHP.SyntaxError
@James Code I've tried: $binarydata64 = pack('H*','40F82C719999999A'); $float64 = unpack("d", $binarydata64);SyntaxError

2 Answers

6
votes
function hex2float($strHex) {
    $hex = sscanf($strHex, "%02x%02x%02x%02x%02x%02x%02x%02x");
    $hex = array_reverse($hex);
    $bin = implode('', array_map('chr', $hex));
    $array = unpack("dnum", $bin);
    return $array['num'];
}

$float = hex2float('40F82C719999999A');
echo $float;

will return 99015.1

0
votes

How to convert back float to 64 bit hex:

function float2hex($num) {
    $bin = pack("d", $num);
    $hex = array_map('ord', str_split($bin));
    $hex = array_reverse($hex);
    $strHex = vsprintf("%02x%02x%02x%02x%02x%02x%02x%02x", $hex);
    return $strHex;
}
$hex = float2hex(99015.100000000000);
echo strtoupper($hex);

will return 40F82C719999999A