all Python 3structterm
struct
module
Pack numbers into bytes and unpack them back using C-struct-like formats: binary files and protocols.
Syntax
import struct
struct is for foreign binary formats laid out as fixed-width fields: file headers, network packets. The first format character sets byte order and alignment: without '<' or '>' the machine's native ones apply and results differ across platforms. For a single integer int.to_bytes is shorter, and for arrays of same-typed numbers use array.
Examples
import struct
data = struct.pack('<HI', 1, 258)
print(data) # → b'\x01\x00\x02\x01\x00\x00'
print(struct.unpack('<HI', data), struct.calcsize('<HI')) # → (1, 258) 6
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy