bitstruct

8.22.1 · active · verified Fri Apr 10

This module performs conversions between Python values and C bit field structs represented as Python byte strings. It offers an interface similar to Python's built-in `struct` module but operates at the bit level. The current version is 8.22.1, and it maintains an active release cadence with recent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to pack Python integers into a compact byte string using a format string, unpack them back, and calculate the size of the packed data. It also shows how to use a pre-compiled format string for repeated operations.

from bitstruct import pack, unpack, calcsize

# Define a format string: u1 (1-bit unsigned), u3 (3-bit unsigned), u4 (4-bit unsigned), s16 (16-bit signed)
fmt = 'u1u3u4s16'

# Pack values into a byte string
packed_data = pack(fmt, 1, 2, 3, -4)
print(f"Packed data: {packed_data}")
# Expected: b'\xa3\xff\xfc'

# Unpack values from the byte string
unpacked_values = unpack(fmt, packed_data)
print(f"Unpacked values: {unpacked_values}")
# Expected: (1, 2, 3, -4)

# Calculate the total number of bits required for the format
size_in_bits = calcsize(fmt)
print(f"Size in bits: {size_in_bits}")
# Expected: 24 (bits)

# Using a compiled format for efficiency
import bitstruct
cf = bitstruct.compile(fmt)
compiled_packed = cf.pack(1, 2, 3, -4)
compiled_unpacked = cf.unpack(compiled_packed)
print(f"Compiled format packed: {compiled_packed}")
print(f"Compiled format unpacked: {compiled_unpacked}")

view raw JSON →