最近測試涉及到了序列字節化相關問題,碰到一個頭疼的問題
buff = struct.pack("3s","B00")
print repr(buff)
輸出:'B00'
buff = struct.pack('i',10172)
print repr(buff)
輸出:"\xbc'\x00\x00"
buff = struct.pack("3si","B00",10172)
print repr(buff)
輸出:"B00\x00\xbc'\x00\x00"
即:struct.pack("3s","B00")+struct.pack('i',10172) != struct.pack("3si","B00",10172)
但struct.pack("!3s","B00")+struct.pack('!i',10172) == struct.pack("!3si","B00",10172)是相等的
問題分析:
為了同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_