it's because when you do:
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
it's not returning a string with [ \
, x
, 0
, ...] but a bytearray containing each number given in hex:
>>> pack('hhl', 1, 2, 3)[0]
'\x00'
so, when you're doing:
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
you're actually trying to unpack a string like I was saying previously. Whereas if you do:
>>> s = pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', s)
(1, 2, 3)
it's working as expected.
Now as @falstru is telling, a way to convert a string with hex into a bytearray that struct can understand is to use binascii.unhexlify
, which handles the endianness and the conversion. You can also do it yourself:
>>> unpack('hhl', str(bytearray([1,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0])))
(1, 2, 3)