處理二進制資料(如整數、浮點數、C 結構體)時,Python 內建 struct 模組提供 pack/unpack 介面,能依指定格式將資料序列化為位元組串流或還原。本文詳解格式字串、檔案模式、常見陷阱與進階技巧。
格式字串由 字序前綴(可選)與 型別代碼 組成:
| 字序前綴 | 含義 |
|---|---|
@ | 原生字序、大小、對齊(預設) |
= | 原生字序、標準大小、無對齊 |
< | Little-endian,標準大小 |
> | Big-endian,標準大小 |
! | 網路序(Big-endian),標準大小 |
| 型別代碼 | C 型別 | Python 型別 | 標準大小 |
|---|---|---|---|
b | signed char | int | 1 |
B | unsigned char | int | 1 |
h | short | int | 2 |
H | unsigned short | int | 2 |
i | int | int | 4 |
I | unsigned int | int | 4 |
l | long | int | 4 |
q | long long | int | 8 |
f | float | float | 4 |
d | double | float | 8 |
s | char[] | bytes | 依長度 |
p | char[] (Pascal string) | bytes | 依長度 |
from struct import pack, unpack
# 寫入:一個 int(4B)、一個 double(8B)、一個 short(2B) = 共 14 bytes
with open('data.bin', 'wb') as f:
f.write(pack('idh', 12345, 67.89, 15))
# 讀取:必須精確指定讀取位元組數
with open('data.bin', 'rb') as f:
data = f.read(4 + 8 + 2) # 14 bytes
a, b, c = unpack('idh', data)
print(a, b, c) # 12345 67.89 15
關鍵點: 必須使用 'wb'/'rb' 二進制模式,否則 Windows 會轉換換行符導致資料損壞。
# 方法 1:ord() 轉整數
with open('data.bin', 'rb') as f:
byte = f.read(1)
val = ord(byte)
print(hex(val))
# 方法 2:struct.unpack
import struct
with open('data.bin', 'rb') as f:
byte = f.read(1)
print(struct.unpack('b', byte)) # signed char
print(struct.unpack('B', byte)) # unsigned char
import binascii
# hex string → bytes
hs = "5B7F888489FEDA"
hb = binascii.a2b_hex(hs) # b'[\x7f\x88\x84\x89\xfe\xda'
# bytes → hex string
hb = b'[\x7f\x88\x84\x89\xfe\xda'
hs = binascii.b2a_hex(hb).decode() # '5b7f888489feda'
with open('test.bin', 'wb') as f:
# 直接寫入位元組字面值
f.write(b'\x5F\x9D\x3E')
# 追加模式
with open('test.bin', 'ab') as f:
f.write(b'\x45\xF3')
unpack 要求緩衝區大小完全等於格式字串對應大小,否則報 error: unpack requires a buffer of size X。'<' 或 '>'。'i' vs 'I',超出範圍會 struct.error。掌握 struct.pack/unpack 格式字串,即可高效處理二進制協定、檔案格式、硬體介面資料。建議搭配 ctypes 或 numpy.frombuffer 處理大量結構化二進制資料。