Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Struct.pack(format, [...]), packed data's size is different though the format is almost the same

Tags:

python

import struct
data = struct.pack('ici', 1, chr(1), 1)
print(len(data))
#12

data = struct.pack('iic', 1, 1, chr(1))
print(len(data))
#9

there seems no difference between two 'data' variables, why the result of the 'len(data)' is difference, one is 12 and the other is 9

like image 570
Carlos Lin Avatar asked Jan 21 '26 08:01

Carlos Lin


1 Answers

This effect is because of alignment and the padding needed to achieve it. If you refer to the Python Standard Library documentation for Struct, it says in section 7.3.2.1 (I'm referring to the Python 2.7 docs):

Notes:
    Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct. 
    No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’. 
    To align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See Examples. 

The standard size of an "i" is four bytes, for a "c" is 1.

In the first "ici" pack, the "c" has to be padded to 32-bit alignment (i.e. by adding three bytes) to be able to add the final "i" - so the total length is 12.

In the "iic" pack, the final "c" does not have to be padded, so the length is 9.

like image 65
DisappointedByUnaccountableMod Avatar answered Jan 23 '26 23:01

DisappointedByUnaccountableMod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!