[SciPy-user] Problem with reading binary file (diffrener result between MATLAB and Python)

Robert Kern robert.kern at gmail.com
Sun Jan 11 08:12:59 EST 2009


On Sun, Jan 11, 2009 at 06:48, Hani Zahiri <H.Zahiri at curtin.edu.au> wrote:
> Hi folks,
>
>
>
> I am trying to translate one of my MATLAB scripts to Python and I am
> experiencing a strange problem (at least to me!) and I am desperetly looking
> for help. The binary file is a raw binary containing header information
> (first 720 bytes) following by radar data. For better illustration and using
> python basic functions, first 800 bytes of the file is look like this:
>
>
>
>>>> fid = open("file_name","rb")
>
>>>> fid.read(800)
>
> '\x00\x00\x00\x012\xc0\x12\x12\x00\x00\x02\xd0A   CEOS-SAR-CCT A A
> 1.00          1AL1 PSRBIMOP    FSEQ       1   4FTYP       5   4FLGT
> 9   4
> 18432 88220                          32   2   8       1   18432   0
> 10976   0   0   0BSQ  1 1 412   87808   0      13 4PB  49 2PB  45 4PB  21
> 4PB  29 4PB                                  97 4PB
> COMPLEX*8                   C*8    0
> 0
>                                                                                                                                                                                                                                             \x00\x00\x00\x022\n\x12\x14\x00\x01X\x9c\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00*\xe0\x00\x00\x00\x00\x00\x00\x00\x00\
> ...
> x00\x00\x07\xd6\x00\x00\x00\x8d\x02\xdd\xfe\x95\x00\x01\x00\x00\x00\x00\x00\x00\x00\x1c\xae\x93\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ix
> ...
>
> \x00\x00\x00\x00I}.\xd0'
>
>
>
> And now the problem is:
>
> If I read the file in MATLAB, let say to find out length of header part, I
> will get the correct answer:
>
>
>
> EDU>> fid=fopen('file_name','r','b');
>
> EDU>> fseek(fid,8,'bof');
>
> EDU>> fread(fid,1,'uint32')
>
>
>
> ans =
>
>
>
>    720
>
>
>
> However if I read this in python I am keep getting this wrong:
>
>>>> fid.seek(8)
>
>>>> scipy.fromfile(fid,'uint32',1)
>
> array([3489792000], dtype=uint32)

I suspect that you are running your Matlab script on a bigendian
machine and your Python script on a littleendian machine. The length
marker in your file is bigendian. Use dtype='>i4' to read it. You will
probably also need to use bigendian dtypes for the rest of the data,
too.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the SciPy-User mailing list