2

Simple question if do the following:

import struct
struct.calcsize("6cHcBHIIQ")

returns 32 when I believe it should be 28.

By doing the following (missing the Q):

import struct
struct.calcsize("6cHcBHII")

it returns 20, which is what I would expect.

and doing:

import struct
struct.calcsize("Q")

returns 8, which is correct.

Why does adding the Q onto the top one result in 12 extra bytes being expected instead of 8?

Python 3, windows machine.

Thanks.

BloodSexMagik
  • 398
  • 1
  • 3
  • 14

2 Answers2

5

Alignment. See https://docs.python.org/3/library/struct.html#struct-alignment for more details.

Try struct.calcsize("=6cHcBHIIQ").

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

You could also minimize the size by realigning these in a better way:

struct.calcsize("QIIHHB6cc")

yields 28,you should generally expect padding to be the culprit in any struct size issues. See Why isn't sizeof for a struct equal to the sum of sizeof of each member? for a good answer on why struct sizes might sometimes be larger than what they seem.

Community
  • 1
  • 1
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks for this. Id I'm unpacking bytes from a file then the format string would need to be in the correct order though would it not? – BloodSexMagik Nov 23 '16 at 12:33