19greg96
19greg96

Reputation: 2591

PHP pack/unpack float in big endian byte order

How can I pack/unpack floats in big endian byte order with php? I got this far with an unpack function, but I'm not sure if this would even work.

function unpackFloat ($float) {
    $n = unpack ('Nn');
    $n = $n['n'];

    $sign = ($n >> 31);
    $exponent = ($n >> 23) & 0xFF;
    $fraction = $n & 0x7FFFFF;
}

Upvotes: 3

Views: 3990

Answers (2)

Ryan Durham
Ryan Durham

Reputation: 81

PHP 7.2 introduced the option to pack floating point numbers with big endian byte order directly:

// float
$bytes = pack('G', 3.1415);

// double precision float
$bytes = pack('E', 3.1415);

https://www.php.net/manual/en/function.pack.php

Upvotes: 3

19greg96
19greg96

Reputation: 2591

After thinking about it for a while I found a pretty easy solution, to use the opposite byte order from the one pack('f') uses.

unpack

unpack('fdat', strrev(substr($data, 0, 4)));

pack

strrev(pack('f', $data));

Upvotes: 5

Related Questions