Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Binary Data Services
The struct module in Python provides functionality for converting between C structs and Python bytes objects. This is essential for binary data processing, file format handling, and network protocol implementation.
Format String Characters
The byte order, size, and alignment in format strings are controlled by these characters ?
| Character | Byte order | Size | Alignment |
|---|---|---|---|
| @ | native | native | native |
| = | native | standard | none |
| < | little-endian | standard | none |
| > | big-endian | standard | none |
| ! | network (= big-endian) | standard | none |
Data Type Format Characters
These format characters map C types to Python types ?
| Format | C Type | Python Type |
|---|---|---|
| c | char | bytes of length 1 |
| b/B | signed/unsigned char | integer |
| h/H | short/unsigned short | integer |
| i/I | int/unsigned int | integer |
| f | float | float |
| d | double | float |
| s | char[] | bytes |
Using Module-Level Functions
The pack() function converts Python values to bytes, while unpack() converts bytes back to Python values ?
import struct
student = (1, b'Rahul', 65.75)
packed = struct.pack('I 5s f', *student)
print('packed data:', packed)
unpacked = struct.unpack('I 5s f', packed)
print('unpacked data:', unpacked)
packed data: b'\x01\x00\x00\x00Rahul\x00\x00\x00\x00\x80\x83B' unpacked data: (1, b'Rahul', 65.75)
Using the Struct Class
Creating a Struct object is more efficient when using the same format multiple times ?
import struct
student = (1, b'Rahul', 65.75)
s = struct.Struct('I 5s f')
packed = s.pack(*student)
print('packed:', packed)
unpacked = s.unpack(packed)
print('unpacked:', unpacked)
packed: b'\x01\x00\x00\x00Rahul\x00\x00\x00\x00\x80\x83B' unpacked: (1, b'Rahul', 65.75)
Working with Named Tuples
You can convert unpacked data directly to a named tuple for better readability ?
import struct
from collections import namedtuple
student = (1, b'Rahul', 65.75)
packed = struct.pack('I 5s f', *student)
Student = namedtuple('Student', 'No Name Marks')
s1 = Student._make(struct.unpack('I 5s f', packed))
print(s1)
print(f"Student Number: {s1.No}, Name: {s1.Name.decode()}, Marks: {s1.Marks}")
Student(No=1, Name=b'Rahul', Marks=65.75) Student Number: 1, Name: Rahul, Marks: 65.75
Conclusion
The struct module enables efficient binary data conversion between Python and C formats. Use module functions for simple operations or the Struct class for repeated operations with the same format.
