A Python module to help you manage your bits
bitstring is a Python module to help make the creation and analysis of all types of bit-level binary data as simple and efficient as possible.
It has been actively maintained since 2006.
March 2024: bitstring 4.2.0b2 released. This is the final beta release before 4.2.
Install the beta with pip install bitstring==4.2.0b2
, or use pip install bitstring
for the latest stable version.
New in 4.2:
Dtype
class can be optionally used to specify types.bitstring.options
object is now the preferred method for changing module options.fromstring
method as another way to create bitstrings from formatted strings.See the release notes for details. Please let me know if you encounter any problems.
Extensive documentation for the bitstring module is available. Some starting points are given below:
You can also try out the interactive walkthrough notebook on binder.
To see what been added, improved or fixed, and also to see what's coming in the next version, see the release notes.
$ pip install bitstring
>>> from bitstring import Bits, BitArray, BitStream, pack
>>> a = BitArray(bin='00101')
>>> b = Bits(a_file_object)
>>> c = BitArray('0xff, 0b101, 0o65, uint6=22')
>>> d = pack('intle16, hex=a, 0b1', 100, a='0x34f')
>>> e = pack('<16h', *range(16))
>>> a = BitArray('0x3348')
>>> a.hex, a.bin, a.uint, a.float, a.bytes
('3348', '0011001101001000', 13128, 0.2275390625, b'3H')
>>> a[10:3:-1].bin
'0101100'
>>> '0b100' + 3*a
BitArray('0x866906690669, 0b000')
>>> b = BitStream('0x160120f')
>>> b.read(12).hex
'160'
>>> b.pos = 0
>>> b.read('uint12')
352
>>> b.readlist('uint12, bin3')
[288, '111']
>>> c = BitArray('0b00010010010010001111') # c.hex == '0x1248f'
>>> c.find('0x48')
(8,)
>>> c.replace('0b001', '0xabc')
>>> c.insert('0b0000', pos=3)
>>> del c[12:16]
>>> from bitstring import Array
>>> a = Array('uint7', [9, 100, 3, 1])
>>> a.data
BitArray('0x1390181')
>>> a[::2] *= 5
>>> a
Array('uint7', [45, 100, 15, 1])
Created in 2006 to help with ad hoc parsing and creation of compressed video files. Maintained and expanded ever since as it became unexpectedly popular. Thanks to all those who have contributed ideas and code (and bug reports) over the years.
Copyright (c) 2006 - 2024 Scott Griffiths