Read Binary data

M

Mars creature

Hi guys,
I am trying to read a binary file created by the following matlab
command:
fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and
wondering how to do it in Python. I googled it but still get
confused.
'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit
float.
Thank you very much!
Jinbo Wang
 
F

Fredrik Lundh

Mars creature said:
I am trying to read a binary file created by the following matlab
command:
fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and
wondering how to do it in Python. I googled it but still get
confused.
'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit
float.


f = open("a.bin", "rb") # read binary data
s = f.read() # read all bytes into a string

import array, sys

a = array.array("f", s) # "f" for float
if sys.byteorder != "big":
a.byteswap()

</F>
 
M

Mars creature

f = open("a.bin", "rb") # read binary data
s = f.read() # read all bytes into a string

import array, sys

a = array.array("f", s) # "f" for float
if sys.byteorder != "big":
a.byteswap()

</F>

Thanks Fredrik! I appreciate it!
The only thing is that a = array.array("f", s) should be a =
array.array("d", s) as the data is double precision.
Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top