Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Binary Data Services (Dịch vụ dữ liệu nhị phân)

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:

CharacterByte orderSizeAlignment
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone

Format characters chỉ kiểu C type và Python type tương ứng:

FormatC TypePython type
xpad byteno value
ccharbytes length 1
b/Bsigned/unsigned charinteger
?_Boolbool
h/Hshort/unsigned shortinteger
i/Iint/unsigned intinteger
l/Llong/unsigned longinteger
ffloatfloat
ddoublefloat
schar[]bytes
pchar[]bytes
Pvoid *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)