Open In App

struct.pack() in Python

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The struct.pack() function in Python converts values like integers and floats into a bytes object based on a specified format. This is useful for storing or transmitting data in binary format.

Example:

Python
import struct

# Pack an integer (10) as an unsigned short (2 bytes, big-endian)
s = struct.pack('>H', 10)
print(s)  

Output
b'\x00\n'

Explanation

  • >H: The format string specifies big-endian (>) and unsigned short (H, 2 bytes).
  • 10: The integer being packed.
  • b'\x00\n': The byte representation of the number 10 in big-endian format.

Syntax of struct.pack() Method

struct.pack(format, value1, value2, ...)

Parameters

  • format: A format string that specifies the data type(s) to be packed.
  • value1, value2, ...: The values to be packed according to the format.

Return Value

  • Returns a bytes object containing the packed values.

Understanding Format Strings

The format string in struct.pack() defines how data should be stored in bytes. Some common format codes are:

Format CodeData TypeSize (bytes)
bSigned char1
BUnsigned char1
hSigned short2
HUnsigned short2
iSigned int4
IUnsigned int4
fFloat4
dDouble8

Examples of struct.pack() method

1. Packing a Float

Python
import struct
n = 3.14
s = struct.pack('>f', n)  
print(s)

Output
b'@H\xf5\xc3'

Explanation:

  • This code uses struct.pack() to pack the float 3.14 into binary format with big-endian byte order ('>f').
  • '>f': > specifies big-endian byte order. f is for packing a float (4 bytes).

2. Packing Multiple Values

Python
import struct
s = struct.pack('>Ih', 1000, -20)
print(s) 

Output
b'\x00\x00\x03\xe8\xff\xec'

Explanation: This code uses struct.pack() to pack an unsigned integer (1000) and a signed short (-20) into a big-endian binary format ('>Ih').

Common Errors and How to Fix Them

1. Mismatched Format and Data

If we provide a format that doesn't match the data type, Python raises a struct.error.

Python
import struct
# Trying to pack a float with an integer format
struct.pack('H', 3.14)  # struct.error: required argument is not an integer

Solution: Use the correct format, e.g., 'f' for floats.

2. Incorrect Number of Values

Providing more or fewer values than required by the format string causes an error.

Python
import struct
struct.pack('H', 10, 20)  # struct.error: pack expected 1 items for packing (got 2)

Solution: Ensure the number of values matches the format string.



Next Article
Article Tags :
Practice Tags :

Similar Reads