bitstring
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
- breaking Version 4.0 introduced several backward incompatible changes, including dropping support for Python 2.7 and older Python 3 versions (now requires Python 3.7+), removing `ConstBitArray` and `BitString` aliases, and changing the default behavior of `uint` interpretation.
- breaking The `cut()` method in version 4.0 now yields the final bits even if they are shorter than the requested cut size. Previously, it might have raised an exception or omitted partial cuts.
- breaking Overwrites extending beyond the end of a bitstring in version 4.0 will now extend the bitstring rather than raising an exception.
- gotcha When initializing `Bits` or `BitArray` from integers, omitting quotes around hexadecimal, octal, or binary string representations will result in creating a bitstring of that *integer value* in zero bits, not a bitstring parsed from the string. For example, `BitArray(0xff01)` creates 65281 zero bits.
- deprecated The `bitstring.lsb0` and `bitstring.bytealigned` module-level variables for changing options are deprecated. Use `bitstring.options.lsb0` and `bitstring.options.bytealigned` instead.
Install
-
pip install bitstring
Imports
- Bits
from bitstring import Bits
- BitArray
from bitstring import BitArray
- BitStream
from bitstring import BitStream
- pack
from bitstring import pack
- Array
from bitstring import Array
- ConstBitArray
from bitstring import Bits
- BitString
from bitstring import BitArray
Quickstart
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}")