在Python中将字节转换为浮点数 [英] Convert Bytes to Floating Point Numbers in Python

查看:1444
本文介绍了在Python中将字节转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ C>>>> 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 @'


I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?

解决方案

>>> 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@'

这篇关于在Python中将字节转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆