CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-bitarray

Efficient arrays of booleans with comprehensive sequence operations, bitwise operations, and specialized functionality for encoding/decoding variable-length prefix codes.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-operations.mddocs/

Core Operations

Core bitarray operations including creation, modification, sequence operations, and bitwise arithmetic. These operations form the foundation for all bit manipulation tasks.

Capabilities

Bitarray Construction

Creates bitarray objects from various initializers with configurable bit-endianness and optional buffer support.

class bitarray:
    """Efficient array of booleans stored as packed bits"""
    def __init__(self, 
                 initializer: Union[int, str, Iterable[int], None] = 0,
                 endian: Union[str, None] = 'big',
                 buffer: Any = None) -> None:
        """
        Create a bitarray object.
        
        Args:
            initializer: Initial value - int (length), str ('01' format), iterable of ints, or bitarray
            endian: Bit-endianness - 'big' or 'little'  
            buffer: Buffer object for memory mapping
        """

Usage Examples:

from bitarray import bitarray

# Different initialization methods
a = bitarray(8)                    # 8 zero bits
b = bitarray('10110')              # From binary string
c = bitarray([1, 0, 1, 1, 0])      # From list
d = bitarray(c)                    # Copy constructor
e = bitarray(8, 'little')          # Little-endian

Sequence Operations

Standard sequence operations including appending, extending, inserting, removing, and accessing elements.

def append(self, value: int) -> None:
    """Append single bit (0 or 1) to end of bitarray"""

def extend(self, x: Union[str, Iterable[int]]) -> None:
    """Extend bitarray with bits from string or iterable"""

def insert(self, i: int, value: int) -> None:
    """Insert bit at position i"""

def pop(self, i: int = -1) -> int:
    """Remove and return bit at position i (default last)"""

def remove(self, value: int) -> None:
    """Remove first occurrence of bit value"""

def clear(self) -> None:
    """Remove all bits"""

def copy(self) -> bitarray:
    """Return shallow copy"""

def reverse(self) -> None:
    """Reverse bitarray in-place"""

def sort(self, reverse: int = 0) -> None:
    """
    Sort bits in-place.
    
    Args:
        reverse: Sort order - 0 for ascending (0s first), 1 for descending (1s first)
    """

Usage Examples:

a = bitarray('101')
a.append(1)           # '1011'
a.extend('00')        # '101100'
a.insert(2, 1)        # '1011100'
bit = a.pop()         # Returns 0, a becomes '101110'
a.remove(0)           # Remove first 0: '11110'
a.reverse()           # '01111'

Search and Analysis

Functions for searching bit patterns and analyzing bitarray contents.

def count(self, 
          sub_bitarray: Union[bitarray, int] = 1,
          start: int = 0, 
          stop: Optional[int] = None,
          step: int = 1) -> int:
    """Count occurrences of sub_bitarray in slice"""

def find(self, 
         sub_bitarray: Union[bitarray, int],
         start: int = 0,
         stop: Optional[int] = None, 
         right: bool = False) -> int:
    """Find first occurrence, return -1 if not found"""

def index(self,
          sub_bitarray: Union[bitarray, int],
          start: int = 0,
          stop: Optional[int] = None,
          right: bool = False) -> int:
    """Find first occurrence, raise ValueError if not found"""

def search(self,
           sub_bitarray: Union[bitarray, int],
           start: int = 0,
           stop: Optional[int] = None,
           right: bool = False) -> Iterator[int]:
    """Return iterator of all occurrence positions"""

def all(self) -> bool:
    """True if all bits are 1 (or bitarray is empty)"""

def any(self) -> bool:
    """True if any bit is 1"""

Usage Examples:

a = bitarray('110101101')

# Counting
print(a.count())           # 6 (count of 1s)
print(a.count(0))          # 3 (count of 0s)
print(a.count('10'))       # 2 (count of '10' pattern)

# Searching
pos = a.find('101')        # 2 (first occurrence)
pos = a.find('111')        # -1 (not found)
positions = list(a.search('1'))  # [0, 1, 3, 5, 6, 8]

# Boolean tests
print(a.all())             # False
print(a.any())             # True

Bit Manipulation

Direct bit manipulation operations including inversion, filling, and setting all bits.

def invert(self, i: Optional[int] = None) -> None:
    """Invert all bits, or bit at position i if specified"""

def setall(self, value: int) -> None:
    """Set all bits to value (0 or 1)"""

def fill(self) -> int:
    """Fill unused bits in last byte with 0, return number filled"""

def bytereverse(self, start: int = 0, stop: Optional[int] = None) -> None:
    """Reverse bit order within each byte"""

Usage Examples:

a = bitarray('10110')

# Bit manipulation
a.invert()              # '01001'
a.invert(2)             # '01101' (invert bit at position 2)
a.setall(1)             # '11111'
a.setall(0)             # '00000'

# Byte operations
a = bitarray('1011001010110')
a.bytereverse()         # Reverse bits within bytes

Magic Methods and Operators

Comprehensive operator support for arithmetic, comparison, and bitwise operations.

# Sequence protocol
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
def __getitem__(self, key: Union[int, slice]) -> Union[int, bitarray]: ...
def __setitem__(self, key: Union[int, slice], value: Union[int, bitarray]) -> None: ...
def __delitem__(self, key: Union[int, slice]) -> None: ...
def __contains__(self, item: Union[int, bitarray]) -> bool: ...

# Arithmetic operations  
def __add__(self, other: bitarray) -> bitarray: ...
def __iadd__(self, other: bitarray) -> bitarray: ...
def __mul__(self, n: int) -> bitarray: ...
def __imul__(self, n: int) -> bitarray: ...
def __rmul__(self, n: int) -> bitarray: ...

# Bitwise operations
def __and__(self, other: bitarray) -> bitarray: ...
def __or__(self, other: bitarray) -> bitarray: ...
def __xor__(self, other: bitarray) -> bitarray: ...
def __invert__(self) -> bitarray: ...
def __lshift__(self, n: int) -> bitarray: ...
def __rshift__(self, n: int) -> bitarray: ...

# In-place bitwise operations
def __iand__(self, other: bitarray) -> bitarray: ...
def __ior__(self, other: bitarray) -> bitarray: ...
def __ixor__(self, other: bitarray) -> bitarray: ...
def __ilshift__(self, n: int) -> bitarray: ...
def __irshift__(self, n: int) -> bitarray: ...

# Comparison operations
def __eq__(self, other: bitarray) -> bool: ...
def __ne__(self, other: bitarray) -> bool: ...
def __lt__(self, other: bitarray) -> bool: ...
def __le__(self, other: bitarray) -> bool: ...
def __gt__(self, other: bitarray) -> bool: ...
def __ge__(self, other: bitarray) -> bool: ...

Usage Examples:

a = bitarray('1010')
b = bitarray('1100')

# Sequence operations
print(len(a))           # 4
print(a[1])             # 0
print(a[1:3])           # bitarray('01')
a[1] = 1               # a becomes '1110'

# Arithmetic
c = a + b              # '11101100' (concatenation)
c = a * 3              # '111011101110' (repetition)
a += b                 # In-place concatenation

# Bitwise operations
result = a & b         # AND: '1100'
result = a | b         # OR:  '1110'  
result = a ^ b         # XOR: '0010'
result = ~a            # NOT: '0001'
result = a << 2        # Left shift: '101000'
result = a >> 1        # Right shift: '010'

# In-place bitwise
a &= b                 # In-place AND
a |= b                 # In-place OR
a ^= b                 # In-place XOR
a <<= 2                # In-place left shift
a >>= 1                # In-place right shift

Properties

Bitarray properties providing metadata about the object's state and configuration.

@property
def endian(self) -> str:
    """Bit-endianness: 'big' or 'little'"""

@property  
def nbytes(self) -> int:
    """Number of bytes used to store bitarray"""

@property
def padbits(self) -> int:
    """Number of padding bits in last byte"""

@property
def readonly(self) -> bool:
    """True if bitarray is read-only"""

Usage Examples:

a = bitarray('1010110', 'little')

print(a.endian)         # 'little'
print(a.nbytes)         # 1 (7 bits = 1 byte)
print(a.padbits)        # 1 (8-7 = 1 padding bit)
print(a.readonly)       # False

# Buffer info for advanced use
info = a.buffer_info()
print(f"Address: {info.address}")
print(f"Bytes: {info.nbytes}")
print(f"Endian: {info.endian}")

Memory and Buffer Operations

Advanced memory management and buffer protocol support for integration with NumPy and other libraries.

def buffer_info(self) -> BufferInfo:
    """Return named tuple with buffer information"""

def __buffer__(self, flags: int, /) -> memoryview:
    """Return memoryview for buffer protocol"""

def __release_buffer__(self, buffer: memoryview, /) -> None:
    """Release buffer"""

def _freeze(self) -> None:
    """Make bitarray immutable (internal method used by frozenbitarray)"""

The bitarray class supports Python's buffer protocol, enabling zero-copy operations with NumPy arrays, memory-mapped files, and other buffer-aware objects.

Install with Tessl CLI

npx tessl i tessl/pypi-bitarray

docs

advanced-features.md

core-operations.md

creation-conversion.md

index.md

utility-functions.md

tile.json