Intermediate LevelPython
How do you pack and unpack C-style binary data structures and network packets using the struct module?
❓ Interview Prompt: Explain `struct` module, byte-order format strings (`>I2s`), `struct.pack()`, `struct.unpack()`, and binary network socket parsing.
The 'struct' module converts between Python values and C structs represented as binary 'bytes' objects:
Primary Use Case:
Parsing low-level binary network socket protocols, binary file headers, and hardware serial streams:
•
'struct.pack('>I2s', 1024, b'OK')': Packs Big-endian 4-byte unsigned int and 2-byte string into binary bytes.
Code Implementation Example
python
import struct
# Pack 32-bit int and 2-byte header into C binary representation
binary_packet = struct.pack('>I2s', 8080, b'OK')
print('Packed Bytes:', binary_packet)
# Unpack binary bytes back to Python values
port, status = struct.unpack('>I2s', binary_packet)
print(f'Port: {port}, Status: {status.decode()}')💡Packing and unpacking binary protocol bytes using the struct module.
🎯 Interview Key Takeaway
Use the struct module to parse low-level C binary data structures and network packets.
#struct#Binary Data#Byte Order#Networking#Intermediate
Back to all Python Questions→