Python中如何使用struct模板,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
struct模板主要函數有:
pack(v1, v2, ...)
unpack(string)
pack_into(buffer, offset, v1, v2, ...)
unpack_from(buffer, offset=0)
下文一一介紹
先來看看官方說明:
pack(fmt, v1, v2, ...):
Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.
就是把values:v1, v2按照對應fmt(format)方式轉換為string.
來看個栗子:
>>> import struct >>> >>> v1 = 1 >>> v2 = 'abc' >>> bytes = struct.pack('i3s', v1, v2) >>> bytes '\x01\x00\x00\x00abc'
這里的fmt就是'i3s'
,什么意思呢?其中i
就是integer,即整數,后面的s
對應string。在上面的栗子中,abc
是長度為3的字符串,所以就有了3s
.
這里有一個完整的fmt列表:
fmt.png
同樣,先看看官方文檔
unpack(fmt, string)
Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The result is a tuple even if it contains exactly one item. The string must contain exactly the amount of data required by the format (len(string) must equal calcsize(fmt)).
簡單說來,就是把string按照對應的fmt形式解析出來。注意,結果返回的是一個tuple
舉個栗子
>>> bytes = '\x01\x00\x00\x00abc' >>> v1, v2 = struct.unpack('i3s', bytes) >>> v1 1 >>> v2 'abc'
這就把上面的v1,v2還原回去了。
注意,當返回值只有一個時:
>>> a = 2 >>> a_pack = struct.pack('i',a) >>> a_unpack = struct.unpack('i',a_pack) #此處得到的a_unpack為tuple >>> a_unpack (2,) >>> a_unpack, = struct.unpack('i',a_pack) #此處得到的a_unpack為int >>> a_unpack 2
這里穿插一下字節的順序,大小,和對齊問題
下面有個表
order.png
如果在fmt字符串前加上了'<',那么字節將會采用little-endian即小端的排列方式,如果是'>'會采用big-endian即大端的排列方式。默認的是'@'方式
舉個栗子
>>> a = 2 >>> a_pack = struct.pack('i',a) #這是默認的,機器不同可能會不同,我這里默認為字節按little-endian順序排列 >>> a_pack '\x02\x00\x00\x00' >>> >>> a_pack2 = struct.pack('>i',a) # '>'即big-endian >>> a_pack2 '\x00\x00\x00\x02' >>> >>> a_pack3 = struct.pack('<i',a) #'<'即little-endian >>> a_pack3 '\x02\x00\x00\x00'
如果不按默認的小端或大端字節排列,加上'<'或'>',unpack就要留意了
>>> a = 2 >>> a_pack2 = struct.pack('>i',a) #big-endian >>> a_pack2 '\x00\x00\x00\x02' >>> a_unpack, = struct.unpack('<i',a_pack2) #little-endian >>> a_unpack 33554432 >>> a_unpack2, = struct.unpack('>i', a_pack2) #big-endian >>> a_unpack2 2
如上所示,如果pack與unpack操作的字節順序不一致,把little-endian和big-endian亂搞,就會導致數據搞亂
其實,struct是類似于C語言中的struct結構體方式存儲數據的。故這里有一個數據的對齊方式問題。如果在內存為32位(即4GB)機器中,一般是以4 bytes對齊的。CPU一次讀?。醋止?,然后放入對應的cache(緩存)中。
看個栗子
struct A{ char c1; int a; char c2; }
結構體A會占用多少內存大小呢?直覺上可能是 1+4+1 = 6 字節,但一般來說,其實是12字節!在第一個char變量c1占用了一字節后,由于是4字節對齊的,int變量a不會插在c1后面,而是把c1后面隱式的補上3個字節,然后把a放在了下面的那行中,最后把char變量c2放到a下面。
再看看下面的
struct A{ char c1; char c2; int a; }
這種情形,結構體A會占用多少內存呢?答案是8字節。原理同上,先把char變量c1放上去,和c1同行的還有3字節,一看下一個char變量c2才1字節,于是就把c2接在c1后面了,此時還剩2字節,但是已經不夠int了,故只能填充上2字節,然后另起一行。
想想為什么要這樣呢?這豈不是浪費了內存了?!從某種意義上說,確實是浪費了內存,但這卻提高了CPU的效率!
想想這種情景模式:假設內存中某一行已經先放了一字節的char變量c, 下一個是輪到int變量a了,它一共占4字節內存,先是拿出3字節放在了變量c的后面,然后再拿最后的1字節放在下面一行。
如果CPU想讀取a變量該怎么辦?它應該讀?。泊?!一次讀?。匙止?,一次讀?。弊止?。故這速度真是拖了,慢了一倍??!如果變量a是另起一行的話,只要讀取一次就夠了,直接把4字節取走。
有了上了的簡單認識,就好理解這個函數是干什么了的
文檔君說
struct.calcsize(fmt)
Return the size of the struct (and hence of the string) corresponding to the given format.
簡單說來,就是根據fmt計算出struct占用了內存的多少字節
舉個栗子
>>> struct.calcsize('ci') 8 >>> struct.calcsize('ic') 5
查查上面的format表可知,c
對應于char,大小為1字節;i
對應于int,大小為4字節。所以,出現了上面情況,至于原因,不再累贅。只是最后的ic
輸出了5,我猜,在struct所占用內存行中的最后一行是不用再padding即填充了。
上面舉的栗子都是加了padding的,如果不填充呢?
>>> struct.calcsize('<ci') 5 >>> struct.calcsize('@ci') 8
倘若在fmt前加上了'<','>','=','!'這些,則不會padding,即不填充。默認的或是'@'則會。
在具體講解之前,先來看幾個函數預熱一下
這個模塊用于二進制和ASCII碼之間的轉換,下面介紹幾個函數
binascii.b2a_hex(data)
binascii.hexlify(data)
Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The resulting string is therefore twice as long as the length of data.
簡單說來,就是用十六進制表示二進制數。
舉個栗子
>>> import binascii >>> s = 'abc' >>> binascii.b2a_hex(s) '616263' >>> binascii.hexlify(s) '616263'
binascii.a2b_hex(hexstr)
binascii.unhexlify(hexstr)
Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex()
hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise a TypeError is raised.
簡單說來,就是上面函數的反操作,即把十六進制串轉為二進制數據
舉個栗子
>>> binascii.a2b_hex('616263') 'abc' >>> binascii.unhexlify('616263') 'abc'
文檔說
struct.pack_into(fmt, buffer, offset, v1, v2, ...)
Pack the values v1, v2, ...
according to the given format, write the packed bytes into the writable buffer starting at offset. Note that the offset is a required argument.
簡單說來,就是把values:v1, v2, ...打包按格式fmt轉換后寫入指定的內存buffer中,并且可以指定buffer中的offset即偏移量,從哪里開始寫。
struct.unpack_from(fmt, buffer[, offset=0])
Unpack the buffer according to the given format. The result is a tuple even if it contains exactly one item. The buffer must contain at least the amount of data required by the format (len(buffer[offset:])
must be at least calcsize(fmt)).
簡單說來,就是從內存中的指定buffer區讀取出來,然后按照fmt格式解析??梢灾付?em>offset,從buffer的哪個位置開始讀取。
相比于前面的pack, unpack,這兩個函數有什么作用呢?我們也可以看出區別,就是多了buffer這東東,內存中的一個緩沖區。在前面,pack需要將values v1, v2打包放入內存中某個區域,而這某個區域是程序內部定的,可能會讓出很多的空間給它放,這有點浪費了。其次,如果每次間斷性的來一些vlaues,然后又要開辟新的空間,這效率有點慢了,拖時間??!那還不如我們一次性給定算了,而且我們可以指定多少內存給它,這樣就不會浪費內存了。
舉個栗子
import struct import binascii import ctypes vals1 = (1, 'hello', 1.2) vals2 = ('world', 2) s1 = struct.Struct('I5sf') s2 = struct.Struct('5sI') print 's1 format: ', s1.format print 's2 format: ', s2.format b_buffer = ctypes.create_string_buffer(s1.size+s2.size) #開出一塊buffer print 'Before pack:',binascii.hexlify(b_buffer) s1.pack_into(b_buffer,0,*vals1) s2.pack_into(b_buffer,s1.size,*vals2) print 'After pack:',binascii.hexlify(b_buffer) print 'vals1 is:', s1.unpack_from(b_buffer,0) print 'vals2 is:', s2.unpack_from(b_buffer,s1.size)
結果輸出:
s1 format: I5sf s2 format: 5sI Before pack: 00000000000000000000000000000000000000000000000000000000 After pack: 0100000068656c6c6f0000009a99993f776f726c6400000002000000 vals1 is: (1, 'hello', 1.2000000476837158) vals2 is: ('world', 2)
看完上述內容,你們掌握Python中如何使用struct模板的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。