需要處理二進制數據時使用,例如在socket發送、接受的數據中。因爲在網絡通信中,數據先被打包成結構體(struct)類型,再被打包成二進制字符串流來進行傳輸。所以數據需要打包和拆包。struct模塊的功能就是在python字符串與c結構體之間進行轉化。主要有三個函數。
pack(fmt, v1, v2, …)
作用:按照fmt提供的格式(即v1,v2等python數據類型),將v1,v2…等數據封裝成二進制字符串(相當與c中的結構體的字節流)。例如:
import struct
import binascii
a = ('abc', 1.2, 7)
#packed = struct.pack('3sfI', a[0], a[1], a[2])
packed = struct.pack('3sfI', *a)
print type(packed)
print binascii.hexlify(packed)
其中binascii
用來輸出結果。fmt的結構後面講到。最後的結果爲:
<type 'str'>
61626300010000000000e040
unpack(fmt, string)
作用:按照給定的格式(fmt)解析二進制字節流string,返回解析出來的tuple。
import struct
import binascii
a = ('abc', 1.2, 7)
packed = struct.pack('3sfI', *a)
unpacked = struct.unpack('3sfI', packed)
print type(unpacked)
print unpacked
輸出結果:
<type 'tuple'>
('abc', 1.2000000476837158, 7)
calcsize(fmt)
作用:計算給定的格式(fmt)佔用多少字節的內存。
import struct
size = struct.calcsize('3sfI')
print size
[Output] : 12 # 3*1 + 4 + 4 = 11 按4對齊,即12
format格式轉換對照表
Format | C Type | Python Type | 字節數 |
---|---|---|---|
x | pad byte | no value | 1 |
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 or long | 4 |
l | long | integer | 4 |
L | unsigned long | long | 4 |
q | long long | long | 8 |
Q | unsigned long long | long | 8 |
f | float | float | 4 |
d | double | float | 8 |
s | char[] | string | 1 |
p | char[] | string | 1 |
P | void * | long |
1.每個格式前可以有一個數字,表示個數
2.s格式表示一定長度的字符串,4s表示長度爲4的字符串,但是p表示的是pascal字符串
3.P用來轉換一個指針,其長度和機器字長相關
format字節順序
在format字符串前面加上特定的符號即可以表示不同的字節順序存儲方式。
Character | Byte order | Size and alignment |
---|---|---|
@ | native order | native 湊夠4個字節 |
= | native standard | standard 按原字節數 |
< | little-endian | standard 按原字節數 |
> | big-endian | standard 按原字節數 |
! | network (= big-endian) | standard 按原字節數 |
使用方法是放在fmt的第一個位置,就像’@5s6sif’