Read Binary data

Discussion in 'Python' started by Mars creature, Sep 4, 2008.

  1. 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
     
    Mars creature, Sep 4, 2008
    #1
    1. Advertising

  2. "Mars creature" wrote:

    > 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>
     
    Fredrik Lundh, Sep 4, 2008
    #2
    1. Advertising

  3. On Sep 4, 12:03 pm, Fredrik Lundh <> wrote:
    > "Mars creature" wrote:
    > > 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>


    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!
     
    Mars creature, Sep 4, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Pete Fraser
    Replies:
    4
    Views:
    6,824
    Mike Treseler
    Nov 4, 2004
  2. Doug
    Replies:
    3
    Views:
    4,373
    Bruce Barker
    Nov 4, 2005
  3. John Adams

    read binary data from C file???

    John Adams, Sep 22, 2004, in forum: Java
    Replies:
    15
    Views:
    6,463
    Steve Horsley
    Sep 24, 2004
  4. Albert Tu
    Replies:
    3
    Views:
    536
    Bengt Richter
    Mar 10, 2005
  5. pman

    read binary data problems

    pman, Aug 17, 2006, in forum: C Programming
    Replies:
    3
    Views:
    1,051
    Voral
    Aug 18, 2006
Loading...

Share This Page