struct size not match the total sum of each fields

Viewed 23

How to understand below struct size? I wish to calculate it by sum all items but looks like it's not correct:

import struct

s = struct.Struct('<8s 10I 16s 512s 32s 1024s')
total = 8 + 10 + 16 + 512 + 32 + 1024
print("total:",total)
print("size:",s.size)

The output is:

: total: 1602
: size: 1632

1602 is the total sum of items, but actually the size is 1632!

1 Answers

Each unsigned integer has a standard size of 4 bytes, so the size of 10 unsigned integers, as you denote with 10I, occupies 4 * 10, rather than 10, bytes.

total = 8 + 4 * 10 + 16 + 512 + 32 + 1024 # == 1632
Related