8.52. struct 模块 API 文档

8.52.1. API

def pack(fmt:str,*args)->bytes:...
def unpack(fmt:str,data:bytes,offset=0)->tuple:...
def unpack_from(fmt:str,data:bytes,offset=0)->tuple:...

8.52.2. Examples

8.52.2.1. unpack.py

import struct
unpacked_bytes = struct.unpack('bbhhh', b'\x01\x02\x03\x04\x05\x06\x07\x08')
assert unpacked_bytes[0] == 1
assert unpacked_bytes[1] == 2
assert unpacked_bytes[2] == 1027
assert unpacked_bytes[3] == 1541
assert unpacked_bytes[4] == 2055

unpacked_bytes = struct.unpack('If', b'\x01\x00\x00\x00\x42\x28\xAE\x47')

assert unpacked_bytes[0] == 1
assert unpacked_bytes[1] == 89168.515625

unpacked_string_numbers = struct.unpack(
    '5sIf', b'Hello\x00\x00\x00\x01\x00\x00\x00B(\xaeG')
assert unpacked_string_numbers[0] == b'Hello'
assert unpacked_string_numbers[1] == 1
assert unpacked_string_numbers[2] == 89168.515625

unpacked_mixed_data = struct.unpack(
    'BffI', b'\x01\x00\x00\x00+R\x9aD\x00\x00\x80?P\\\x01\x00')
assert unpacked_mixed_data[0] == 1
assert unpacked_mixed_data[1] == 1234.5677490234375
assert unpacked_mixed_data[2] == 1
assert unpacked_mixed_data[3] == 89168

print('PASS')

8.52.2.2. pack.py

import struct

# Test strings and fixed-length strings
assert struct.pack('5s', b'Hello') == b'Hello'
assert struct.pack('10s', b'World') == b'World\x00\x00\x00\x00\x00'

assert struct.pack(
    'hhl', 1, 2, 3) == b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'

# Test signed short, unsigned short, and signed long
assert struct.pack(
    'hHl', -1, 255, 1234567890) == b'\xff\xff\xff\x00\x00\x00\x00\x00\xd2\x02\x96I\x00\x00\x00\x00'

# Test single precision float and double precision float
assert struct.pack(
    'fd', 3.14159, 123.45678901234567) == b'\xd0\x0fI@\x00\x00\x00\x00\x98L\xfb\x07<\xdd^@'

# Test byte order and alignment
assert struct.pack('>ih5s', 256, 6553,
                   b'Python') == b'\x00\x00\x01\x00\x19\x99Pytho'

# Test combination of multiple values
#! NOT SUPPORTED
# assert struct.pack('chHiIq', b'A', 127, 3268, 2147, 42945, 9220) == \
#     b'A\x00\x7f\x00\xc4\x0c\x00\x00c\x08\x00\x00\xc1\xa7\x00\x00\x04$\x00\x00\x00\x00\x00\x00'

boot_times = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
boot_time_tuple = tuple(boot_times)
boot_time_blob = struct.pack('@10Q', *boot_time_tuple)
# print(boot_time_blob)
assert boot_time_blob == b'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x09\x00\x00\x00\x00\x00\x00\x00'

boot_times_unpack = struct.unpack('@10Q', boot_time_blob)
# print(boot_times_unpack)
assert boot_times_unpack == boot_time_tuple

print('PASS')