[Python 實戰] - No.11 Python Struct 模塊使用

Python提供了一個struct模塊來解決bytes和其他二進制數據類型的轉換

函數 return explain
pack(fmt,v1,v2…) string 按照給定的格式(fmt),把數據轉換成字符串(字節流),並將該字符串返回.
pack_into(fmt,buffer,offset,v1,v2…) None 按照給定的格式(fmt),將數據轉換成字符串(字節流),並將字節流寫入以offset開始的buffer中.(buffer爲可寫的緩衝區,可用array模塊)
unpack(fmt,v1,v2…..) tuple 按照給定的格式(fmt)解析字節流,並返回解析結果
pack_from(fmt,buffer,offset) tuple 按照給定的格式(fmt)解析以offset開始的緩衝區,並返回解析結果
calcsize(fmt) size of fmt 計算給定的格式(fmt)佔用多少字節的內存,注意對齊方式

比較重要的是pack()unpack()兩個函數,上表中的format格式如下:

Character Byte order Size Alignment
@ native native native
= native standard none
< little-endian standard none
> big-endian standard none
! network (= big-endian) standard none
Format C Type Python type Standard size Notes
x pad byte no value
c char string of length 1 1
b signed char integer 1
B unsigned char integer 1
? _Bool bool 1
h short integer 2
H unsigned short integer 2
i int integer 4
I unsigned int integer 4
l long integer 4
L unsigned long integer 4
q long long integer 8 q和Q只適用於64位機器;
Q unsigned long long integer 8 q和Q只適用於64位機器;
f float float 4
d double float 8
s char[] string
p char[] string
P void * integer

每個格式前可以有一個數字,表示這個類型的個數,如s格式表示一定長度的字符串,4i表示四個int

structpack函數把任意數據類型變成bytes

import struct
print(struct.pack("<i",123456))
print(struct.pack("<3s",b'hello'))
print(struct.pack("<5sl",b'hello',123456))
b'@\xe2\x01\x00'
b'hel'
b'hello@\xe2\x01\x00'

unpackbytes變成相應的數據類型:

import struct
mybytes = struct.pack("<5sl",b'hello',123456)
mystr = struct.unpack("<5sl",mybytes)
print(mystr)
(b'hello', 123456)

mybytes 字節流中有兩個部分,一個是長度爲5的string類型,一個是4個bytelong

如果想查看給定的格式佔多少個字節,可以使用calcsize(fmt),用法如下:

print 'l:',calcsize('l')
print '@i:',calcsize('@i')
print '=i:',calcsize('=i')
print '>s:',calcsize('>s')
print '<q:',calcsize('<q')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章