python: struct模块处理二进制数据

struct模块中最重要的三个函数是pack(), unpack(), calcsize()

#pack(fmt, v1, v2, …)
按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)

#unpack(fmt, string)
按照给定的格式(fmt)解析字节流string,返回解析出来的tuple

#calcsize(fmt)
计算给定的格式(fmt)占用多少字节的内存

struct中支持的格式如下表:

Format C Type 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 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|