Given a binary string. Every 4 characters in it have one float value in big-endian format.

$binary_data; // здесь бинарные данные $data_num = 3800; // целое значение - сколько байт данных $bts_float = 4; // 4 символа на значение for ($i = 0; $i < $data_num/$bts_float; $i++) { $tmpbuffer = ''; $index=$i*$bts_float; $tmpbuffer .= $binary_data[$index+3]; $tmpbuffer .= $binary_data[$index+2]; $tmpbuffer .= $binary_data[$index+1]; $tmpbuffer .= $binary_data[$index]; array_push($result_array, unpack("f", $tmpbuffer)); } 

While unpack("G*", $buffer); at least somehow tolerantly discloses, but this is only for PHP 7.0+, and for 5.6 only with the approximate code above.

Error: {"1": - 77.17456817626953}, {"1": - 77.43785858154297}, {"1": - 79.72053527832031} ...

Question: Is it okay with the code? Where did "1" come from?

in Python, it is unpacked like this: struct.unpack('!%df' % block, buffer) , where block = number of values ​​/ 4, buffer - binary data

  • Did you see what you have in tmpbuffer? Judging by the error message it is empty. most likely you have something wise with indexes when getting bytes from the input string. And also look at what intval php.net/manual/ru/function.intval.php is ; its use here is not at all clear - Mike
  • I corrected everything, now it is unpacked, but somehow it is strange. Where does "1" come from? - GarfieldCat

1 answer 1

As the code is written, so it works. I will assume that you look at the result with something like echo json_encode($result_array);

So, if you check the documentation , you can see that the unpack function always returns an array. It is possible to determine the values ​​of the array keys in the format string, but if the keys in the format string are not mentioned, then unpack will use a simple counter of parameters starting from 1 . Accordingly, for a format string of one parameter, the result of unpack will be an associative array with key 1 and value - the unpacked value.

If you need only one value, then transfer it to the result.