Python/struct

維基教科書,自由的教學讀本

有的時候需要用Python處理二進制數據,比如,存取文件、socket操作。可以使用Python的struct模塊來完成。

struct模塊中最重要的三個函數是pack(), unpack(), calcsize()

  • pack(fmt, v1, v2, ...) 按照給定的格式(fmt),把數據封裝成字符串(實際上是類似於c結構體的字節流)
  • unpack(fmt, string) 按照給定的格式(fmt)解析字節流string,返回解析出來的tuple
  • calcsize(fmt) 計算給定的格式(fmt)佔用多少字節的內存

格式描述[編輯]

struct中支持的格式如下表:

Format C 語言數據類型 Python 字節數
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 / 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(表示一定長度的字符串,4s表示長度為4的字符串)
p char[] string 1 (表示的是pascal字符串)
P void * long 和機器字長相關

每個格式前可以有一個數字,表示個數。

可以用格式中的第一個字符來改變對齊方式.定義如下:

字符 字節順序 字節數和對齊方式
@ native native 湊夠4個字節
= native standard 按原字節數
< little-endian standard 按原字節數
> big-endian standard 按原字節數
! network (= big-endian) standard 按原字節數

例子[編輯]

import struct  
  
# 定义数据  
a = b"hello"  
b = b"world!"  
c = 20  
d = 42.56  
  
# 打包  
binStr = struct.pack("5s6sif", a, b, c, d)  
print (len(binStr))
binStr2 = struct.pack("i", c)  
  
# 解包  
e, f, g, h = struct.unpack("5s6sif", binStr)  
print (e, f, g, h )
  
# 注意unpack返回的是tuple,如果不按规定格式书写,则返回值将改变类型  
i, = struct.unpack("i", binStr2)  
print (i)
i = struct.unpack("i", binStr2)  
print (i)
  
# 计算转换字节长度  
print (struct.calcsize("5s6sif"))