Bitarray

3.8.0 · active · verified Sun Mar 29

The bitarray library (current version 3.8.0) provides an efficient object type for representing arrays of booleans, implemented as a C extension for high performance. Bitarrays behave much like standard Python lists, supporting sequence operations like slicing and concatenation, as well as bitwise operations. It allows users to choose between little-endian and big-endian representations, with eight bits packed into one byte in a contiguous memory block. The library maintains an active release cadence, with frequent updates addressing features and bug fixes.

Warnings

Install

Imports

Quickstart

Demonstrates creating bitarray objects, setting individual bits, extending with more bits, and initializing from strings or iterables. It also shows basic bitwise operations.

from bitarray import bitarray

# Create an empty bitarray of length 10, initialized to zeros
a = bitarray(10)
print(f"Initial bitarray: {a} (length: {len(a)})")

# Set individual bits
a[0] = 1
a[3] = 1
print(f"After setting bits: {a}")

# Append bits
a.append(0)
a.extend('101') # Extend with a string of '0's and '1's
print(f"After appending and extending: {a} (length: {len(a)})")

# Initialize from a string or list
b = bitarray('1101_0010') # Underscores are ignored
c = bitarray([True, False, True, True])
print(f"Bitarray from string: {b}")
print(f"Bitarray from list: {c}")

# Perform bitwise operations
d = b & c # Bitwise AND
e = b | c # Bitwise OR
print(f"Bitwise AND (b & c): {d}")
print(f"Bitwise OR (b | c): {e}")

view raw JSON →