Python struct模块
1. struct
struct
是用来解决bytes和其他二进制数据类型的转换的模块,它使得流的操作变得非常简单,完美解决了Python没有字节数据类型的尴尬。
主要功能:
- Python数据类型 ——> “字节串”
- “字节串” ——> Python数据类型
struct.pack
struct的pack函数把任意数据类型变成bytes
- 使用格式:
struct.pack(format, v1, v2, ...)
其中,format
为设置的构建格式,后面有几个输入的值,就设置几个格式字符(后文2.2,当然也可以额外增加2.1的格式)。 - 例子:
struct.pack('>I', 10240099)
,返回生成的字节串b'\x00\x9c@c'
struct.unpack
unpack把bytes变成相应的Python数据类型
- 使用格式:
struct.unpack(format, buffer)
其中,format
为设置的构建格式,这个部分与pack有所不同。 - 例子:
struct.unpack('>IH', b