struct module
This module performs conversions between Python values and C structs represented as Python strings.


In [2]:
from struct import *

1 Convert

Format C Type Python byte-size
x pad byte no value 1
c char string of length 1 1
b signed char integer 1
B unsigned char integer 1
? Bool bool 1
h short integer 2
H unsigned short integer 2
i int integer 4
I unsigned int integer or long 4
l long integer 4
L unsigned long long 4
q long long long 8
Q unsigned long long long 8
f float float 4
d double float 8
s char[] string 1
p char[] string 1

2 byte order

Character Byte order Size and alignment
@ native native
= native standard
< little-endian standard
> big-endian standard
! network (= big-endian) standard

3 function


In [3]:
pack('hhl', 1, 2, 3)


Out[3]:
'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'

In [4]:
unpack('hhl', '\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00')


Out[4]:
(1, 2, 3)