struct --- 将字节串解读为打包的二进制数据 — Python 3.8.3 文档 https://docs.python.org/zh-cn/3.8/library/struct.htmlhtml
源代码: Lib/struct.pypython
此模块能够执行 Python 值和以 Python bytes
对象表示的 C 结构之间的转换。 这能够被用来处理存储在文件中或是从网络链接等其余来源获取的二进制数据。 它使用 格式字符串 做为 C 结构布局的精简描述以及与 Python 值的双向转换。git
注解github
默认状况下,打包给定 C 结构的结果会包含填充字节以使得所涉及的 C 类型保持正确的对齐;相似地,对齐在解包时也会被归入考虑。 选择此种行为的目的是使得被打包结构的字节能与相应 C 结构在内存中的布局彻底一致。 要处理平台独立的数据格式或省略隐式的填充字节,请使用 standard
大小和对齐而不是 native
大小和对齐:详情参见 字节顺序,大小和对齐方式。api
某些 struct
的函数(以及 Struct
的方法)接受一个 buffer 参数。 这将指向实现了 缓冲协议 并提供只读或是可读写缓冲的对象。 用于此目的的最多见类型为 bytes
和 bytearray
,但许多其余可被视为字节数组的类型也实现了缓冲协议,所以它们无需额外从 bytes
对象复制便可被读取或填充。数组
struct — Interpret bytes as packed binary data — Python 3.8.3 documentation https://docs.python.org/3.8/library/struct.html网络
struct
— Interpret bytes as packed binary dataSource code: Lib/struct.pyide
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.函数
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.
Several struct
functions (and methods of Struct
) take a buffer argument. This refers to objects that implement the Buffer Protocol and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes
and bytearray
, but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes
object.