Atom

binary.pack()

Serializes one scalar, record or fixed array.

Signature

binary.pack(descriptor, value[, order])

Parameters

Packable descriptor/layout, convertible scalar or matching packed compound value, and optional byte order.

Returns

New packed u8 bytes.

Behavior

Recursively writes scalar bytes and zeroes record padding.

Errors

Invalid order/layout, failed conversion, mismatched packed shape or invalid view.

Example

Atom
use binary
assert(binary.hex(binary.pack(u16, 258, 'big')) == '0102')

Pack one integer in big-endian order

A byte order says which byte should come first.

Atom
use binary
bytes = binary.pack(u16, 258, 'big')
print(binary.hex(bytes))
Output
0102

The two bytes are 01 and 02 in that order.

Pack a record

Pass the same layout that describes the value you created.

Atom
use binary
layout = binary.layout({x = u8, y = u8})
point = create(layout)
point.x = 1
point.y = 2
print(binary.hex(binary.pack(layout, point)))
Output
0102

Each field occupies one byte in this layout.