首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python struct 模組詳解:二進位資料打包與解析實戰

     編輯:更多程式設計知識

Python 沒有原生 bytes 型別(Python 2 以 str 兼任),處理二進位協議、檔案格式、網路封包時,struct 模組是連接 Python 物件與 C 風格二進位結構的關鍵橋樑。本文完整解析格式字元、位元組序、實戰解析 BMP 檔頭。

核心函式

函式用途簽名
packPython 值 → bytespack(fmt, v1, v2, ...)
unpackbytes → Python 值元組unpack(fmt, buffer)
calcsize格式字串佔用位元組數calcsize(fmt)

格式字元完整對照表

字元C 型別Python 型別大小說明
xpad byte無1填充位元組
ccharbytes (長度1)1
bsigned charint1
Bunsigned charint1
hshortint2
Hunsigned shortint2
iintint4
Iunsigned intint4
llongint4
Lunsigned longint4
qlong longint8
Qunsigned long longint8
ffloatfloat4單精度
ddoublefloat8雙精度
schar[]bytesn固定長度字串
pchar[]bytesnPascal 字串(首位元組為長度)

位元組序前綴(關鍵!)

前綴序適用場景
@原生預設,視平台而定(不建議跨平台用)
=原生標準無對齊,標準大小
<Little-endianIntel x86、BMP、WAV、大多數檔案格式
>Big-endian (Network)網路協議 (IP/TCP)、Java、Motorola 68k
!Network (= >)網路標準序,明確語意

基礎範例

import struct

# 32-bit 無號整數,Big-endian
packed = struct.pack('>I', 10240099)
print(packed)           # b'\x00\x9c@c'
print(struct.unpack('>I', packed))  # (10240099,)

# 組合:Big-endian, uint32 + uint16
data = struct.pack('>IH', 4042322160, 32896)
print(struct.unpack('>IH', data))  # (4042322160, 32896)

# 浮點數
struct.pack('>f', 3.14159)
struct.pack('>d', 3.141592653589793)

實戰:解析 BMP 檔頭

BMP 採 Little-endian (<):

import struct

def parse_bmp_header(filepath):
    with open(filepath, 'rb') as f:
        header = f.read(30)  # 讀前 30 位元組
    
    if len(header) < 30:
        raise ValueError('檔案太小,非有效 BMP')
    
    # 格式:2字元 + 4整數*4 + 2短整數*2 = 30 bytes
    # 

Struct 物件導向介面(效能更好)

# 預編譯格式,重複使用避免重新解析格式字串
bmp_header_struct = struct.Struct('

進階技巧

變長資料處理

# 字串長度不固定:先讀長度,再讀內容
# 格式: bytes:
    return struct.pack('

對齊與填充

>>> struct.calcsize('ci')   # char + int,可能有 3 bytes padding
8
>>>> struct.calcsize('=ci') # 標準大小,無對齊
5

跨平台序列化務必使用 = 或 </> 明確指定,避免 @ 原生模式導致不同架構不相容。

適用場景與替代方案

場景推薦工具
簡單二進位協議、檔案頭解析struct
複雜巢狀結構、陣列、指標ctypes / construct
高效能數值陣列numpy / array 模組
通用序列化msgpack / protobuf / pickle

總結

struct 是 Python 處理二進位資料的基石,掌握格式字元、位元組序前綴、Struct 物件重用三大核心,即可輕鬆解析網路封包、二進位檔案格式、硬體裝置通訊協議。記住:跨平台必須顯式指定位元組序。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved