Convert 64 bit hexadecimal to float in PHP

随声附和 提交于 2021-02-18 17:08:48

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/34067202/convert-64-bit-hexadecimal-to-float-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!