struct 模块(作用是在网络传输时转换为标准的C语言格式,然后从C语言格式转化成python语言,python底层实现的代码是C语言,可能计算机比较容易懂C语言)
This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.
此模块执行Python值和表示为Python 对象的C 结构之间的转换bytes。这可用于处理存储在文件中的二进制数据或来自网络连接以及其他来源。它使用 Format Strings作为C结构布局的简洁描述以及与Python值的预期转换。
Note By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.
注意 默认情况下,打包给定C 结构的结果包括填充字节,以便维护所涉及的C类型的正确对齐; 类似地,在拆包时考虑对齐。选择此行为是为了使压缩结构的字节与相应C 结构的内存中的布局完全对应。要处理与平台无关的数据格式或省略隐式填充字节,请使用standard大小和对齐而不是 native大小和对齐:有关详细信息,请参阅字节顺序,大小和对齐。
struct模块中常用的函数
struct.pack(fmt, v1, v2, …)
Return a bytes object containing the values v1, v2, … packed according to the format string fmt. The arguments must match the values required by the format exactly.
struct.pack_into(fmt,buffer,offset,v1,v2,… )
根据格式字符串fmt打包值v1,v2,… 并将打包字节写入从位置偏移开始的可写缓冲区缓冲区。请注意,offset是必需参数。
struct.unpack(fmt, buffer)
Unpack from the buffer buffer (presumably packed by pack(fmt, …)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().
struct.unpack_from(fmt,buffer,offset = 0 )
根据格式字符串fmt从位置偏移处开始从缓冲区解包。结果是一个元组,即使它只包含一个项目。缓冲区的大小(以字节为单位,减去偏移量)必须至少为格式所需的大小,如下所示。calcsize()
struct.calcsize(fmt)
Return the size of the struct (and hence of the bytes object produced by pack(fmt, …)) corresponding to the format string fmt.
struct.calcsize(fmt )
返回与格式字符串fmt对应的struct(以及生成的bytes对象 )的大小。pack(fmt, …)
1 例
import struct
ret = struct.pack('i', 90988994) # i int integer 4
print(ret, len(ret)) # b'\xb6\x8f\x04\x00' 4 (C语言中短数字结构为四位十六进制字节)
num = struct.unpack('i', ret)
print(num[0]) # 90988994
2 打包/解包三个整数的基本示例:
from struct import *
>>>pack('hhl', 1, 2, 3) # l long integer 4 两个h表示重复两次
b'\x01\x00\x02\x00\x03\x00\x00\x00'
>>>calcsize('hhl')
8
>>>unpack('hhl', b'\x01\x00\x02\x00\x03\x00\x00\x00')
(1, 2, 3)