View on GitHub

A Python module to help you manage your bits

bitstring is a Python module that makes the creation, manipulation and analysis of binary data as simple and natural as possible.

Bitstrings can be constructed from integers, floats, hex, octal, binary, bytes or files. They can also be created and interpreted using flexible format strings.

Bitstrings can be sliced, joined, reversed, inserted into, overwritten, etc. with simple methods or using slice notation. They can also be read from, searched and replaced, and navigated in, similar to a file or stream.

Internally the bit data is efficiently stored in byte arrays, the module has been optimized for speed, and excellent code coverage is given by over 400 unit tests.

Written by Scott Griffiths and released under a permissive open source licence for you to use however you like.


News

For latest information see the Releases page


Download

Get the latest version from PyPI, either directly or via easy_install / pip.

Documentation

http://packages.python.org/bitstring Latest documentation

Some quick links to useful parts of the docs:


Examples

See the user manual for more examples.

Creation:

>>> a = BitArray('0b00101') # 5 bits long
    >>> b = Bits(a_file_object) # Treat file as array of bits.
    >>> c = BitArray('0xff, 0b101, 0o65, uint:6=22') # Many initialisers joined together
    >>> d = pack('intle:16, hex=a, 0b1', 100, a='0x34f') # Create using bit-wise pack function
    >>> e = pack('<16h', *range(16))

Different interpretations, slicing and concatenation:

>>> a = BitArray('0x1af')
    >>> a.hex, a.bin, a.uint # Different interpretations using properties
    ('1af', '000110101111', 431)
    >>> a[10:3:-1].bin # Slice with negative step
    '1110101'
    >>> 3*a + 'int:20=40'
    BitArray('0x1af1af1af00028')

Reading data sequentially.

>>> b = BitStream('0x160120f')
    >>> b.read('hex:12') # Read 12 bits, and interpret as hex
    '160'
    >>> b.pos = 0
    >>> b.read('uint:12') # Read those same bits, but interpret as integer
    352
    >>> b.readlist('uint:12, bin:3') # Multiple reads
    [288, '111']

Searching, inserting and deleting:

>>> c = BitStream('0b00010010010010001111') # c.hex == '1248f'
    >>> c.find('0x48') # Note that found byte wasn't byte-aligned
    True
    >>> c.replace('0b001', '0xabc') # Replace all 3-bit occurrences with 12-bits
    >>> c.insert('0b0000')
    >>> del c[4:12]