why struct.pack behave like this

Dave Angel davea at ieee.org
Thu May 20 11:44:00 EDT 2010


Xie&Tian wrote:
> Hi
>
> When I use struct to pack binary data, I found this interesting behaviour:
>
>   
>>>> import struct
>>>> struct.pack('B', 1)
>>>>         
> '\x01'
>   
>>>> struct.pack('H', 200)
>>>>         
> '\xc8\x00'
>   
>>>> struct.pack('BH',1, 200)
>>>>         
> '\x01\x00\xc8\x00'
>   
>>>> struct.calcsize('BH')
>>>>         
> 4
>
> Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"?
>
>
>   
To quote the help:

 >>By default, C numbers are represented in the machine’s native format 
and byte order,
 >>and properly aligned by skipping pad bytes if necessary (according to 
the rules used by the C compiler).

C's standard rules say that when a smaller type is followed by a larger 
one, padding is used so that the second field is aligned according to 
its size.  So a H type will be aligned to a 2byte boundary.  If you had 
two B's before it, no padding would be added.

In C, you can use a compiler switch or a pragma to override standard 
alignment.  Similarly, here you can use a prefix like "=" to override 
the native alignment rules.

DaveA





More information about the Python-list mailing list