struct 模块示例

January 30, 2026

struct 模块示例

本文档介绍 struct 模块的二进制打包与解包。示例来源:doc/pikapython.com/examples/struct/pack.pyunpack.py

模块简介

struct 提供 pack(fmt, ...)unpack(fmt, buffer),用于与 C 结构体或协议数据交互。内嵌示例:

import struct
buf = struct.pack('hh', 1, 2)
a, b = struct.unpack('hh', buf)
assert a == 1 and b == 2

示例代码

pack 打包(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'

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)
boot_times_unpack = struct.unpack('@10Q', boot_time_blob)
assert boot_times_unpack == boot_time_tuple

print('PASS')

说明:格式符 h/H/l/Q 为短整/无符号短整/长整/无符号长整,f/d 为单/双精度浮点,s 为定长字符串,> 大端、@ 本机对齐。

unpack 解包(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

print('PASS')

说明:b 有符号字节,I 无符号整型,f 单精度浮点;解包顺序与格式符一一对应。

注意事项

  • 格式符集合以 PikaPython/设备文档为准,部分格式(如 chHiIq 组合)可能未支持。
  • 字节序与对齐会影响跨设备通信,需与对方约定一致。

相关链接