struct Module Examples


struct Module Examples

This document introduces struct module’s binary packing and unpacking. , unpack.py.

Module Introduction

struct provides pack(fmt, .) and unpack(fmt, buffer) for interacting with C structs or protocol data. Built-in example:

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

Example Code

pack Packing (pack.py excerpt)

#!pika
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')
#!pika

Note: Format characters h/H/l/Q are short int/unsigned short/long int/unsigned long, f/d are single/double float, s is fixed-length string, > big-endian, @ native alignment.

unpack Unpacking (unpack.py)

#!pika
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')
#!pika

Note: b signed byte, I unsigned int, f single float; unpacking order corresponds one-to-one with format characters.

Notes

  • Format character set follows PikaPython/device documentation, some formats (like chHiIq combinations) may not be supported.
  • Byte order and alignment affect cross-device communication, need to agree with peer.