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:
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)
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.