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.