Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 631
Razor Storm Avatar asked Jun 08 '11 22:06

Razor Storm


People also ask

Does IEEE 754 float Python?

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.

How do I read a binary file in Python?

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.

Is floating point 32-bit?

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.


1 Answers

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)) 
like image 171
Marcelo Cantos Avatar answered Oct 16 '22 15:10

Marcelo Cantos