phpfloating-pointhexyii2-advanced-app

PHP convert hex to float


Hi I am trying to convert the hex value into float the method I am using is

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('4019999a');
echo $float;

Output

The output it's returning is 6.4000015258789 but in actual it should be 2.4

See reference


Solution

  • Your problem is that you are interpreting the value in little endian byte order. This gives you the incorrect value of 6.4, which is actually -6.3320110435437E-23. Additionally, you are unpacking this as a double-precision float. It's not. It's single precision (only 4 bytes wide).

    function hex2float($strHex) {
        $hex = sscanf($strHex, "%02x%02x%02x%02x%02x%02x%02x%02x");
        $bin = implode('', array_map('chr', $hex));
        $array = unpack("Gnum", $bin);
        return $array['num'];
    }
    
    $float = hex2float('4019999a');
    echo $float;
    

    This gives you the correct value of 2.4.

    An easier way to do this is var_dump(unpack('G', hex2bin('4019999a'))[1]); which also gives you the correct value.