python struct.pack中的对齐字节问题

最近测试涉及到了序列字节化相关问题,碰到一个头疼的问题html

buff = struct.pack("3s","B00")
    print repr(buff)c++

输出:'B00'测试

 buff = struct.pack('i',10172)
 print repr(buff)url

输出:"\xbc'\x00\x00"spa

buff = struct.pack("3si","B00",10172)
print repr(buff)code

输出:"B00\x00\xbc'\x00\x00"htm

即:struct.pack("3s","B00")+struct.pack('i',10172) != struct.pack("3si","B00",10172)blog

但struct.pack("!3s","B00")+struct.pack('!i',10172) == struct.pack("!3si","B00",10172)是相等的ip

问题分析:编译器

为了同c中的结构体交换数据,还要考虑有的c或c++编译器使用了字节对齐,一般是以4个字节为单位的32位系统,故而struct根据本地机器字节顺序转换.能够用格式中的第一个字符来改变对齐方式.定义以下:

Character Byte order Size and alignment
@ native native            凑够4个字节
= native standard        按原字节数
< little-endian standard        按原字节数
> big-endian standard       按原字节数
! network (= big-endian)

standard       按原字节数

使用方法是放在fmt的第一个位置,就像'@5s6sif'

 

参见以下

http://www.coder4.com/archives/3838

http://www.cnblogs.com/gala/archive/2011/09/22/2184801.html

http://zhidao.baidu.com/link?url=Wd7SipMBMz7-lCTtnV3kUmjF4OMlRqZZUtfY0Zb3SqF5HKsCbwUBJFw8s2FfpTTv55Y-o-YHctDEfJoQ_ILTYAM8-sOWvOPS4aJtlHffNZ_

相关文章
相关标签/搜索