Convert IEEE754 to hex in PHP

2019-09-11 01:18发布

For a project I need to read in information from MQTT. The payload is filled with protobuf information, that needs to be converted.

For a certain value I receive 5.6904566139035E-28 as float. Using http://www.exploringbinary.com/floating-point-converter/ I can convert this when I tick single and raw hexadecimal value, then I receive 12345678, the value I should have (I know what is sent).

But now I need to do that conversion in PHP. I haven't any idea how this could be done. After some reading I figured out it is a Floating Point, but how to convert this like done on that website.

Is there someone that can help me with this!

Thanks a lot!

1条回答
太酷不给撩
2楼-- · 2019-09-11 01:50

With the quite cryptic pack and unpack functions, it can be done in a one-liner:

function rawSingleHex($num) {
    return strrev(unpack('h*', pack('f', $num))[1]);
}

This "packs" the number as its binary representation, then "unpacks" it in an array with one element: the binary representation in hexadecimal format. This format has the digits in the reversed order, so the function reverses that in the final result.

Call it by passing the floating point number:

echo rawSingleHex(5.6904566139035E-28);

Output:

12345678

Without pack/pack

(this was my original answer, but with the first option being available, this is not the advised way to proceed)

The binary format is explained in Wikipedia's article on the Single-precision floating-point format.

Here is a PHP function that implements the described procedure:

function rawSingleHex($num) {
    if ($num == 0) return '00000000';
    // set sign bit, and add another, higher one, which will be stripped later 
    $sign = $num < 0 ? 0x300 : 0x200;
    $significant = abs($num);
    $exponent = floor(log($significant, 2));
    // get 24 most significant binary bits before the comma: 
    $significant = round($significant / pow(2, $exponent-23));
    // exponent has exponent-bias format:
    $exponent += 127;
    // format: 1 sign bit + 8 exponent bits + 23 significant bits,
    //         without left-most "1" of significant
    $bin = substr(decbin($sign + $exponent), 1) . 
           substr(decbin($significant), 1);
    // assert that result has correct number of bits:
    if (strlen($bin) !== 32) {
        return "unexpected error";
    }
    // convert binary representation to hex, with exactly 8 digits
    return str_pad(dechex(bindec($bin)), 8, "0", STR_PAD_LEFT);
}

It outputs the same as in the first solution.

查看更多
登录 后发表回答