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.
Introduction to the Python float typeThe C double type usually implements IEEE 754 double-precision binary float, which is also called binary64. Python float uses 8 bytes (or 64 bits) to represent real numbers. Unlike the integer type, the float type uses a fixed number of bytes.
To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.
Single-precision floating-point format (sometimes called FP32 or float32) is a computer number format, usually occupying 32 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With