Binary and Encoding Modules

struct

Pack Python values into fixed binary layouts and unpack them using format strings. Choose explicit byte order and standard sizes for interchange; native layouts may include platform-specific padding. The buffer must match the layout and integer fields must fit their declared size.

Formal Syntax & Structure

python syntaxpython
import struct

Return Value

module

Module namespace available through import; import is a statement, not a value-returning expression.

Working Example

Example Snippetpython
import structpacket = struct.pack(">HB", 258, 7)print(packet.hex())print(struct.unpack(">HB", packet))
Python Reference