Binary Data Encoding
The struct module
- Allows binary structures to be packed into a string
- Useful if you need to interact with a binary network protocol
- Or if you need to create a binary data structure for a C program.
Packing data with pack(fmt, v1, v2, ...)
- Packs the values v1, v2, and so on according to a format string
- Format codes and corresponding C datatypes
'x' Pad byte 'I' unsigned int
'c' char 'l' long
'b' signed char 'L' unsigned long
'B' unsigned char 'f' float
'h' short 'd' double
'H' unsigned short 's' char[]
'i' int 'P' void *
- Example
s = struct.pack("hhii", 34, 73, 162773, 2222)
s = struct.pack("is", len(t), t)
|