Python binary reading issue

I am trying to read a binary (which is a matrix in Matlab) in Python. But it's hard for me to read the file and convert the bytes to the correct values.

A binary file consists of a sequence of 4 byte numbers. The first two numbers are the number of rows and columns, respectively. My friend gave me the Matlab function that he wrote, and does it with fwrite. I would like to do something like this:

f = open(filename, 'rb')
rows = f.read(4)
cols = f.read(4)
m = [[0 for c in cols] for r in rows]
r = c = 0
while True:
    if c == cols:
        r += 1
        c = 0
    num = f.read(4)
    if num:
        m[r][c] = num
        c += 1
    else:
        break

But whenever I use f.read (4), I get something like "\ x00 \ x00 \ x00 \ x04" (this particular example should represent 4), and I cannot calculate its conversion to the correct number ( using int, hex or nothing like that works). I came across struct.unpack, but that didn't seem to help much.

( , python f.read() - ), Matlab:

4     4     2     4
2     2     2     1
3     3     2     4
2     2     6     2

'\x00\x00\x00\x04\x00\x00\x00\x04@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\xc0\x00\x00@\x80\x00\x00?\x80\x00\x00@\x80\x00\x00@\x00\x00\x00'

, 4 5-8 4, 4x4. 4,4,2,4,2,2,2,1 ..

, !

+3
2

, struct, . , - 4- , 4- big-endian . -, , , - , . . ():

for j in cols:
  for i in rows:
    write Aij to file

. , , :

import struct 

def readMatrix(f):
    rows, cols = struct.unpack('>ii',f.read(8))
    m = [ list(struct.unpack('>%df' % rows, f.read(4*rows)))
             for c in range(cols)
        ]
    # transpose result to return
    return zip(*m)

:

>>> from StringIO import StringIO
>>> f = StringIO('\x00\x00\x00\x04\x00\x00\x00\x04@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\xc0\x00\x00@\x80\x00\x00?\x80\x00\x00@\x80\x00\x00@\x00\x00\x00')
>>> mat = readMatrix(f)
>>> for row in mat:
...     print row
...     
(4.0, 4.0, 2.0, 4.0)
(2.0, 2.0, 2.0, 1.0)
(3.0, 3.0, 2.0, 4.0)
(2.0, 2.0, 6.0, 2.0)
+2
rows = f.read(4)
cols = f.read(4)

4- . ,

import struct

rowsandcols = f.read(8)
rows, cols = struct.unpack('=ii', rowsandcols)

struct.unpack.

+7

Source: https://habr.com/ru/post/1752726/


All Articles