I want to reverse the packing of the following code:
struct.pack("<"+"I"*elements, *self.buf[:elements])
I know "<" means little endian and "I" is unsigned int. How can I use struct.unpack to reverse the packing?
I want to reverse the packing of the following code:
struct.pack("<"+"I"*elements, *self.buf[:elements])
I know "<" means little endian and "I" is unsigned int. How can I use struct.unpack to reverse the packing?
struct.pack
takes non-byte values (e.g. integers, strings, etc.) and converts them to bytes
. And conversely, struct.unpack
takes bytes
and converts them to their 'higher-order' equivalents.
For example:
>>> from struct import pack, unpack
>>> packed = pack('hhl', 1, 2, 3)
>>> packed
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpacked = unpack('hhl', packed)
>>> unpacked
(1, 2, 3)
So in your instance, you have little-endian unsigned integers (elements
many of them). You can unpack them using the same structure string (the '<' + 'I' * elements
part) - e.g. struct.unpack('<' + 'I' * elements, value)
.
Example from: https://docs.python.org/3/library/struct.html
Looking at the documentation: https://docs.python.org/3/library/struct.html
obj = struct.pack("<"+"I"*elements, *self.buf[:elements])
struct.unpack("<"+"I"*elements, obj)
Does this work for you?
© 2022 - 2024 — McMap. All rights reserved.