Integer to bytes and bytes to integer transform.

[plum.int] Module Reference

The plum.int module provides the IntX transform for converting an integer number into bytes and bytes into an integer number. This reference page demonstrates creating and using a IntX transform as well as provides API details.

The examples shown on this page require the following setup:

>>> from plum.array import ArrayX
>>> from plum.int import IntX
>>> from plum.utilities import pack, unpack

Basic Use

The IntX transform accepts the following arguments:

nbytes:format size in bytes (any positive integer)
byteorder:"big" or "little" (default)
signed:True or False (default)
name:transform name (for representations including dump format column)

For example:

>>> uint8 = IntX(nbytes=1)
>>> sint16 = IntX(nbytes=2, byteorder="big", signed=True)

Use the transform to specify a format when using the pack() and unpack() utility functions or when using other high level transforms:

>>> fmt = [uint8, sint16]
>>>
>>> bindata = pack([1, -2], fmt)
>>> bindata.hex()
'01fffe'
>>>
>>> unpack(fmt, bindata)
[1, -2]
>>>
>>> array2x2 = ArrayX(fmt=uint8, dims=(2, 2))
>>>
>>> bindata = pack([[1, 2], [3, 4]], fmt=array2x2)
>>> bindata.hex()
'01020304'
>>>
>>> unpack(array2x2, bindata)
[[1, 2], [3, 4]]

Tip

Use sys.byteorder as the IntX transform byteorder argument to get the same byte order as the architecture of the machine your script is running on.

API Reference

class plum.int.IntX(nbytes: int, byteorder: Union[Literal[little], Literal[big]] = 'little', *, signed: bool = False, dref: Union[Type[plum.data.Data], plum.transform.Transform, None] = None, name: Optional[str] = None)

Integer to bytes and bytes to integer transform.

byteorder

Byte order (“little” or “big”).

name

Transform format name (for repr and dump “Format” column).

nbytes

Transform format size in bytes.

signed

Signed integer.

pack(value: Any) → bytes

Pack value as formatted bytes.

Raises:PackError if type error, value error, etc.
pack_and_dump(value: Any) → Tuple[bytes, plum.dump.Dump]

Pack value as formatted bytes and produce bytes summary.

Raises:PackError if type error, value error, etc.
unpack(buffer: bytes) → Any

Unpack value from formatted bytes.

Raises:UnpackError if insufficient bytes, excess bytes, or value error
unpack_and_dump(buffer: bytes) → Tuple[Any, plum.dump.Dump]

Unpack value from bytes and produce packed bytes summary.

Raises:UnpackError if insufficient bytes, excess bytes, or value error