changzhi
changzhi

Reputation: 2709

Python struct.calcsize length

>>>import struct
>>>size_a = struct.calcsize('10s')
size_a = 10
>>>size_b = struct.calcsize('iii')
size_b = 12
>>>size_c = struct.calcsize('10siii')
size_c = 24

Could someone tell me why size_c is 24 rather than 22(10 + 12) ?

Upvotes: 8

Views: 4590

Answers (1)

ohmu
ohmu

Reputation: 19761

This has to do with alignment. Any particular type (byte, integer, etc.) can only begin at an offset that is a multiple of its standard size.

  • A byte string s can begin at any offset because its standard size is 1.

  • But a 32-bit integer i can only begin at an offset with a multiple of 4 (its size). E.g., 0, 4, 8, 12, etc.

So, to analyze the struct 10siii let's first dissect the 10 byte string.

Offset: 0 1 2 3 4 5 6 7 8 9
        s----------------->

10s takes up the first 10 bytes which is to be expected. Now the following 3 integers.

                            1 1 1 1 1 1 1 1 1 1 2 2 2 2
Offset: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
        s-----------------> x x i-----> i-----> i----->

Each integer spans 4 bytes, but each can only begin at an offset that's a multiple of 4 (i.e., 8, 12, 16, 20, not 10). Since the beginning byte string occupies 10 bytes, it has to be padded by 2 bytes to allow the integers to be at a proper offset. And thus you end up with a total struct size consisting of: 10 (beginning byte string) + 2 (padding) + 12 (3 integers) = 24 byte struct.

Upvotes: 15

Related Questions