Convert Bytes to Floating Point Numbers in Python

匿名 (未验证) 提交于 2019-12-03 08:39:56

问题:

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?

回答1:

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


回答2:

You'll want the struct package.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!