Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does struct.unpack need 2 extra bytes?

I have the following struct.unpack call that fails:

struct.unpack('14x4x2i2xh8x2i', b'\0'*46)

Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    struct.unpack('14x4x2i2xh8x2i', b'\0'*46)
struct.error: unpack requires a buffer of 48 bytes

I’ve added up the number of bytes required by the format multiple times, and I always come up with a total of 46 bytes. But obviously the error says it’s not enough. Why am I coming up short?

The following does produce the expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct.unpack('14x4x2i2xh8x2i', b'\0'*48)

(0, 0, 0, 0, 0)

>Solution :

By default struct expects types to be aligned. Since i is 4 bytes, it’s 2 bytes of padding are assumed to get the offset to a multiple of 4.

You can use the = flag at the beginning of the format string to indicate that values are packed rather than aligned.

struct.unpack('=14x4x2i2xh8x2i', b'\0'*46)

See the documentation of Byte Order, Size, and Alignment. You should probably actually use < rather than =, since BMP integers are stored in little-endian format.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading