Read Binary data

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mars creature

    Read Binary data

    Hi guys,
    I am trying to read a binary file created by the following matlab
    command:
    fid=fopen('a.bi n','w','b'); fwrite(fid,a,'r eal*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
  • Fredrik Lundh

    #2
    Re: Read Binary data

    "Mars creature" wrote:
    I am trying to read a binary file created by the following matlab
    command:
    fid=fopen('a.bi n','w','b'); fwrite(fid,a,'r eal*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>

    Comment

    • Mars creature

      #3
      Re: Read Binary data

      On Sep 4, 12:03 pm, Fredrik Lundh <fred...@python ware.comwrote:
      "Mars creature" wrote:
      I am trying to read a binary file created by the following matlab
      command:
      fid=fopen('a.bi n','w','b'); fwrite(fid,a,'r eal*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!

      Comment

      • mblume

        #4
        Re: Read Binary data

        Am Thu, 04 Sep 2008 18:03:54 +0200 schrieb Fredrik Lundh:
        >
        > I am trying to read a binary file [...]
        >
        >
        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()
        >
        For more complicated structures, the struct module may help.

        HTH.
        Martin

        Comment

        Working...