Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python struct.calcsize length

Tags:

python

>>>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) ?

like image 500
changzhi Avatar asked Feb 08 '14 04:02

changzhi


1 Answers

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.

like image 149
Uyghur Lives Matter Avatar answered Oct 22 '22 07:10

Uyghur Lives Matter