Search code examples
pythonfile-ioconvertersbinaryfilesunpack

How to unpack a struct in Python?


I need to unpack a .bin file. The code used to make the file packed the data like so:

x = ''
x = x + struct.pack('q', random.randint(0, MAX_NUM))
x = x + struct.pack('q', random.randint(0, MAX_NUM))

When I do a f.read(16), where 16 is the size of the data I want to read at a time, and print it out I get:

print out of .bin data

I understand that the 'q' means that the data being packed in a long long, and I have tried to use the struct.unpack() to try to unpack the data, but I can't seem to get the correct syntax on how to unpack it.

So how would I go about unpacking this information?


Solution

  • To pack two random numbers into a string x:

    In [6]: x = struct.pack('2q', random.randint(0, MAX_NUM), random.randint(0, MAX_NUM))
    

    To unpack those numbers from the string:

    In [7]: struct.unpack('2q', x)
    Out[7]: (806, 736)
    

    Saving and reading from a file

    Even if we save x in a file and then read it back later, the unpacking procedure is the same:

    In [8]: open('tmpfile', 'w').write(x)
    
    In [9]: y = open('tmpfile', 'r').read()
    
    In [10]: struct.unpack('2q', y)
    Out[10]: (806, 736)