[plum] Tutorial: Packing Bytes¶
This tutorial demonstrates the various methods for packing Python objects into a sequence of bytes.
The tutorial examples use the following setup:
>>> from plum.bigendian import uint8, uint16
>>> from plum.structure import Structure, member
>>> from plum.utilities import pack
>>>
>>> class MyStruct(Structure):
... m1: int = member(fmt=uint16)
... m2: int = member(fmt=uint8)
...
Pack Utility Function¶
The following example shows a simple use of the pack()
utility function
for packing a Python object into a bytes sequence.
>>> pack(1, uint16)
b'\x00\x01'
The reference API and tutorial pages thoroughly cover the variations and won’t be repeated here.
Transform Pack Methods¶
All plum
transforms support a pack()
method that accepts a value
and produces a sequence of bytes based on the properties of the transform:
>>> uint16.pack(1)
b'\x00\x01'
>>>
>>> MyStruct.pack(MyStruct(m1=1, m2=2))
b'\x00\x01\x02'
Data store instances that have transform properties also support an “instance” (“i” for short) pack method to simplify obtaining the byte sequence:
>>> MyStruct(m1=1, m2=2).ipack()
b'\x00\x01\x02'