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 aVALUEinto a sequence of raw bytes representing the value in binary form.ARGSspecify what encoding to use for the representation; they are type-specific (see below for a list). Thepackoperator returns abytesinstance 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 typeTYPEfrom a binary representationDATA.ARGSspecify what encoding to expect forDATA. Theunpackoperator returns a 2-tuple(VALUE, REMAINDER)whereVALUEis the parsed value, andREMAINDERis any bytes left over fromDATAthat weren’t used for parsing the value. If parsing fails,unpackthrows anInvalidValueexception.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.