简体   繁体   中英

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:

打印出.bin数据

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?

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)

You used 2 "q"s to pack it, so use 2 "q"s to unpack it.

>>> struct.unpack('2q', 'abcdefghijklmnop')
(7523094288207667809, 8101815670912281193)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM