BloodSexMagik
BloodSexMagik

Reputation: 398

Python struct format character sizes, why is it bigger than it should be?

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.

Upvotes: 2

Views: 803

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

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.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249103

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

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

Upvotes: 5

Related Questions