Python Struct - Binary Data Packing Cheat Sheet

A Programming › Python cheat sheet in English by hmerjay

A concise reference guide for Python's struct module, used for converting between Python values and C-style binary data.

3,291 views 399 downloads 17 Nov 2025 History

Basic

struct.pa­ck(­format, v1, v2, ...)
struct.un­pac­k(f­ormat, string)
struct.pa­ck_­int­o(f­ormat, buffer, offset, v1, v2, ...)
struct.un­pac­k_f­rom­(fmt, buffer­[,o­ffset = 0])

Examples

pack('h­hl', 1, 2, 3)
b'\x­00­\x01­\x0­0\x­02­\x00­\x0­0\x­00­\x03­'
unpack­('hh­l', b'\x­00­\x01­\x0­0\x­02­\x00­\x0­0\x­00­\x03­')
(1, 2, 3)

Byte Order

@
native
=
native
<
little­-endian
>
big-endian
!
network (= big-en­dian)

Format Characters

c
char
1
b/B
signed­/un­signed char
1
?
bool
1
h/H
signed­/un­signed short
2
i/I
signed­/un­signed int
4
l/L
signed­/un­signed long
4
q/Q
signed­/un­signed long long
8
f
float
4
d
double
8
s
bytes

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.