Doe
Doe

Reputation: 195

How to read a binary file of type complex64 values in Python

I have a binary file that contains several complex numbers of type complex64? (i.e. four bytes of type float for the real part and another four bytes for the imaginary part). The real and imaginary parts are multiplexed so that the real part is stored first and followed by the imaginary part.

Upvotes: 3

Views: 3217

Answers (1)

Jacques Gaudin
Jacques Gaudin

Reputation: 16988

I was able to reproduce the error you encounter by creating an array of complex64 from [0, 2+j, -3.14-7.99j], saving it to a file and reading it as Python built-in complex type.

The issue is that the built-in complex type has the size of a C double which, depending on your plateform, may differ from 32-bits (256 bits on my machine).

You must use numpy.fromfile('file_name', dtype=numpy.complex64) to read your file correctly, i.e. make sure the complex numbers are read as two 32-bits floating point numbers.

Upvotes: 2

Related Questions