5.2.7. Packing / Unpacking Values
A few of Spicy’s atomic types support low-level conversion from, or into, a binary representation through two operators:
pack(VALUE, ARGS)
turns aVALUE
into a sequence of raw bytes representing the value in binary form.ARGS
specify what encoding to use for the representation; they are type-specific (see below for a list). Thepack
operator returns abytes
instance containing the encoded data.As an example,
pack(uint16(513), spicy::ByteOrder::Network)
returns\x02\x01
, which is 513 in network byte order.unpack<TYPE>(DATA, ARGS)
parses a value of typeTYPE
from a binary representationDATA
.ARGS
specify what encoding to expect forDATA
. Theunpack
operator returns a 2-tuple(VALUE, REMAINDER)
whereVALUE
is the parsed value, andREMAINDER
is any bytes left over fromDATA
that weren’t used for parsing the value. If parsing fails,unpack
throws anInvalidValue
exception.As an example,
unpack<uint16>(b"\x02\x01XYZ", spicy::ByteOrder::Network)
returns the tuple(513, b"XYZ")
.
The following table summarizes the types that currently support packing/unpacking, along with the encoding arguments that the operators expect for each:
Type |
|
|
Links |
---|---|---|---|
|
|
||
|
|
||
|
|
Real Type [1], Byte Order |
Note
[1] Packing a real
value as IEEE754_Single
may loose information.