3

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. :(

SyntaxError
  • 31
  • 1
  • 2

2 Answers2

6
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

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