Convert hexadecimal to float

2

I am working with php and I get some coordinates in hexadecimal format (this can not be changed because it is a message that is received from the SigFox network). The values that are received are C40B3986 and 4564AF79 and the values in float would be -556.8988 and 3658.967 . I used this code that I found by google to do the transformation:

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'];
}

But the results obtained differ considerably from what was expected: 2.9704245515207E-65 and 6.7994010560009E-225 . Can someone help me out?

    
asked by miguelex 15.10.2018 в 10:54
source

1 answer

2

Here is a feature which can help you:

<?php

$string = "C40B3986";

function hexTo32Float($strHex) {
  $v = hexdec($strHex);
  $x = ($v & ((1 << 23) - 1)) + (1 << 23) * ($v >> 31 | 1);
  $exp = ($v >> 23 & 0xFF) - 127;
  return $x * pow(2, $exp - 23);
}

$float = hexTo32Float($string);
echo "El valor Float de ".$string." es: ".$float."<br>";

?>

This function converts a hexadecimal string to a floating 32-bit IEEE 754 number.

You can see it working here :

Edited

According to the report of @aloMalbarez:

  

it seems like you eat the sign bit so you would have to add it

would look like this:

<?php

$string = "C40B3986";

function hexTo32Float($strHex) {
  $v = hexdec($strHex);
  $x = ($v & ((1 << 23) - 1)) + (1 << 23) * ($v >> 31 | 1);
  $exp = ($v >> 23 & 0xFF) - 127;
  return $x * pow(2, $exp - 23)*($v>>31==0?1:-1);
}

$float = hexTo32Float($string);
echo "El valor Float de ".$string." es: ".$float."<br>";

?>

You can see it with its here .

    
answered by 15.10.2018 / 14:56
source