简体   繁体   English

将字节转换为浮点数?

[英]Convert Bytes to Floating Point Numbers?

I have a binary file that I have to parse and I'm using Python.我有一个必须解析的二进制文件,我正在使用 Python。 Is there a way to take 4 bytes and convert it to a single precision floating point number?有没有办法获取 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只是一点点补充,如果您想要一个浮点数作为 unpack 方法的输出而不是元组,只需编写

>>> 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:如果您有一个包含 X 个浮点数的字节缓冲区,则解包的语法为:

struct.unpack('Xf', ...)

If the values are doubles the unpacking would be:如果值是双倍的,则拆包将是:

struct.unpack('Xd', ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM