bitstring

4.4.0 · active · verified Thu Apr 09

bitstring is a Python library designed for the simple and efficient creation, analysis, and modification of bit-level binary data. It has been actively maintained since 2006 and is currently at version 4.4.0, with a regular release cadence for maintenance and new features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating BitArray objects from various string formats (hexadecimal, binary, octal, formatted integers), packing multiple values into a bitstring, and reading data sequentially from a BitStream.

from bitstring import BitArray, BitStream, pack

# Create a BitArray from a hexadecimal string
a = BitArray('0xff01')
print(f"BitArray 'a': {a.bin} (length: {a.len} bits)")

# Create a BitArray from multiple formats
c = BitArray('0xff, 0b101, 0o65, uint:6=22')
print(f"BitArray 'c': {c.hex} (length: {c.len} bits)")

# Pack values into a bitstring
d = pack('intle:16, hex=a, 0b1', 100, a='0x34f')
print(f"Packed bitstring 'd': {d.bin} (length: {d.len} bits)")

# Read sequentially from a BitStream
b = BitStream('0x160120f')
print(f"Initial BitStream 'b': {b.hex}")
read_hex = b.read(12).hex
print(f"Read 12 bits as hex: {read_hex}, remaining: {b.hex}")
b.pos = 0 # Reset position
read_uint = b.read('uint:12')
print(f"Read 12 bits as uint: {read_uint}")

view raw JSON →