问题
So, long story short, I am trying to 'unpack' some data myself, but I am not able to do so. Fortunately I have the solution, but I cannot figure out the method. Basically, I have this array of data here,
[16 130 164 65 103 136 209 64 19 36 185 190 83]
, and I am told that when 'unpacked' via 'fffB'
, I get:
[ 20.56350708, 6.54790068, -0.36160335, 83]
I know for a fact that this solution is correct, but I am not sure how we attained it.
The context here is that the input array was 'unpacked', using Python's command as so:
struct.unpack_from('fffB', input)
However try as I may, I am unable to understand the exact operation here.
回答1:
First you need to convert the list of numbers to a string since that's what unpack expects:
Unpack from the buffer buffer (presumably packed by pack(fmt, ...)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().
Number in the list can be converted to characters with chr and once you join
them together you have input that can be given to unpack
:
import struct
d = [16, 130, 164, 65, 103, 136, 209, 64, 19, 36, 185, 190, 83]
s = ''.join(chr(x) for x in d) # s = bytearray(d) on Python 3
struct.unpack('fffB', s) # (20.563507080078125, 6.547900676727295, -0.36160334944725037, 83)
Format string fffB
tells unpack
to extract three floats of 4 bytes each and one unsigned character size of 1 byte. In total 13 bytes are extracted which matches the length of your data. The exact specification of format characters can be found from Python documentation.
Note that above example only works with Python 2.x, on Python 3.x you need to convert the list to bytearray instead of string.
来源:https://stackoverflow.com/questions/37095796/how-was-this-data-conversion-performed-exactly