QA
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→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?