最近測試涉及到了序列字節化相關問題,碰到一個頭疼的問題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_