Float to bytes and bytes to float transform.

[plum.float] Module Reference

The plum.float module provides the FloatX transform for converting a floating point number into bytes and bytes into a floating point number. This reference page demonstrates creating and using a FloatX transform as well as provides API details.

The examples shown on this page require the following setup:

>>> from plum.array import ArrayX
>>> from plum.float import FloatX
>>> from plum.utilities import pack, unpack

Basic Use

The FloatX transform accepts the following arguments:

nbytes:format size in bytes, 2, 4, or 8 (half, single, double precision)
byteorder:"big" or "little" (default)
name:transform name (for representations including dump format column)

For example:

>>> float16 = FloatX(nbytes=2, byteorder="big")
>>> float32 = FloatX(nbytes=4, byteorder="big")

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

>>> fmt = [float16, float32]
>>>
>>> bindata = pack([1, -2], fmt)
>>> bindata.hex()
'3c00c0000000'
>>>
>>> unpack(fmt, bindata)
[1.0, -2.0]
>>>
>>> array2x2 = ArrayX(fmt=float16, dims=(2, 2))
>>>
>>> bindata = pack([[1, 2], [3, 4]], fmt=array2x2)
>>> bindata.hex()
'3c00400042004400'
>>>
>>> unpack(array2x2, bindata)
[[1.0, 2.0], [3.0, 4.0]]

Tip

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

API Reference

class plum.float.FloatX(nbytes: int, byteorder: str = 'little', name: Optional[str] = None)

Float to bytes and bytes to float transform.

byteorder

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

name

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

nbytes

Transform format size in bytes.

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