Reading 32 bit signed ieee 754 floating points from a binary file with python?

我的未来我决定 提交于 2019-11-29 06:09:30

问题


I have a binary file which is simple a list of signed 32 bit ieee754 floating point numbers. They are not separated by anything, and simply appear one after another until EOF.

How would I read from this file and interpret them correctly as floating point numbers?

I tried using read(4), but it automatically converts them to a string with ascii encoding.

I also tried using bytearray but that only takes it in 1 byte at a time instead of 4 bytes at a time as I need.


回答1:


struct.unpack('f', file.read(4))

You can also unpack several at once, which will be faster:

struct.unpack('f'*n, file.read(4*n))



回答2:


Take a peek at struct.unpack. Something like the following might work...

f = struct.unpack('f', data_read)



回答3:


import struct
(num,) = struct.unpack('f', f.read(4))


来源:https://stackoverflow.com/questions/6286033/reading-32-bit-signed-ieee-754-floating-points-from-a-binary-file-with-python

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