Module struct trong thư viện Python hữu ích để chuyển đổi giữa C type structs và Python bytes objects. Đạt được qua module-level functions cũng như class Struct và methods.
Conversion functions dùng format string. Byte order, size, alignment trong format string xác định bởi formatting character:
| Character | Byte order | Size | Alignment |
|---|---|---|---|
| @ | native | native | native |
| = | native | standard | none |
| < | little-endian | standard | none |
| > | big-endian | standard | none |
| ! | network (= big-endian) | standard | none |
Format characters chỉ kiểu C type và Python type tương ứng:
| Format | C Type | Python type |
|---|---|---|
| x | pad byte | no value |
| c | char | bytes length 1 |
| b/B | signed/unsigned char | integer |
| ? | _Bool | bool |
| h/H | short/unsigned short | integer |
| i/I | int/unsigned int | integer |
| l/L | long/unsigned long | integer |
| f | float | float |
| d | double | float |
| s | char[] | bytes |
| p | char[] | bytes |
| P | void * | integer |
Các hàm trong module struct:
- pack(): Trả về bytes object chứa values packed theo format string. Formatting characters phải match values required.
- unpack(): Unpack từ buffer theo format string. Kết quả là tuple ngay cả khi chỉ có 1 item.
Ví dụ
import struct
student = (1, b'Rahul', 65.75)
packed = struct.pack('I 5s f', *student)
print('packed data:', packed)
unpacked = struct.unpack('I 5s f', packed)
print('unpacked data:', unpacked)
Kết quả
packed data: b'\x01\x00\x00\x00Rahul\x00\x00\x00\x00\x80\x83B'
unpacked data: (1, b'Rahul', 65.75)
Packing/unpacking cũng đạt được qua methods của class Struct. Tạo Struct object một lần và gọi methods hiệu quả hơn gọi struct functions cùng format vì format string chỉ compile một lần.
Struct(format)
Constructor trả về Struct object mới read/write binary data theo format string.
- pack(): Giống hàm pack(), dùng compiled format.
- unpack(): Giống hàm unpack(), dùng compiled format.
s = struct.Struct('I 5s f')
packed = s.pack(*student)
print(packed)
unpacked = s.unpack(packed)
print(unpacked)
Packed data có thể parse trực tiếp thành named tuple object:
from collections import namedtuple
newstudent = namedtuple('newstudent', 'No Name Marks')
s1 = newstudent._make(struct.unpack('I 5s f', packed))
print(s1)
Kết quả
newstudent(No=1, Name=b'Rahul', Marks=65.75)