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

asked Feb 8, 2014 at 4:04

1 Answer 1

14

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.

answered Feb 8, 2014 at 5:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.