我有一个必须解析的二进制文件,我使用的是 Python。有没有一种方法可以采取4字节,并转换为一个单一的精度浮点数?
>>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write
>>> import struct >>> [x] = struct.unpack('f', b'\xdb\x0fI@') >>> x 3.1415927410125732
If you have more floats then just write
>>> import struct >>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x0b\x01I4') >>> x 3.1415927410125732 >>> y 1.8719963179592014e-07 >>>
I would add a comment but I don't have enough reputation.
Just to add some info. If you have a byte buffer containing X amount of floats, the syntax for unpacking would be:
struct.unpack('Xf', ...)
If the values are doubles the unpacking would be:
struct.unpack('Xd', ...)