当前位置:首页> 正文

在Python中将字节转换为浮点数

在Python中将字节转换为浮点数

Convert Bytes to Floating Point Numbers in Python

我有一个必须解析的二进制文件,并且正在使用Python。 有没有办法占用4个字节并将其转换为单个精度浮点数?


1
2
3
4
5
6
7
>>> 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@'

只需加一点,如果您想将浮点数作为unpack方法的输出而不是元组,则只需编写

1
2
3
>>> [x] = struct.unpack('f', b'\xdb\x0fI@')
>>> x
3.1415927410125732

如果您有更多的浮动,那就写

1
2
3
4
5
6
>>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x0b\x01I4')
>>> x
3.1415927410125732
>>> y
1.8719963179592014e-07
>>>

展开全文阅读

相关内容