Im in no way an experienced python programmer,thats why i believe there may be an obvious answer to this but i just can't wrap my head around the struct.pack and unpack. i have the following code:

struct.pack("<"+"I"*elements, *self.buf[:elements])

I want to reverse the the packing of this, however im not sure how, i know that "<" means little endian and "I" is unsigned int and thats about it, im not sure how to use struct.unpack to reverse the packing.

2

2 Answers

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:

2

Looking at the documentation:

obj = struct.pack("<"+"I"*elements, *self.buf[:elements]) struct.unpack("<"+"I"*elements, obj) 

Does this work for you?

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy