BitArray Module

The BitArray module provides different implementations for efficient bit manipulation in FlexFloat.

Base BitArray Protocol

class flexfloat.BitArray(*args, **kwargs)[source]

Bases: Protocol

Protocol defining the interface for BitArray implementations.

This protocol defines all the methods and properties that a BitArray implementation must provide.

For consistency, all BitArray implementations should order bits as LSB-first, meaning the least significant bit is at index 0 and the most significant bit is at the highest index.

classmethod from_bits(bits=None)[source]

Creates a BitArray from a list of boolean values.

Parameters:

bits (list[bool] | None, optional) – List of boolean values. Defaults to None, which creates an empty BitArray.

Returns:

A BitArray created from the bits.

Return type:

BitArray

classmethod from_float(value)[source]

Converts a floating-point number to a bit array.

Parameters:

value (float) – The floating-point number to convert.

Returns:

A BitArray representing the bits of the floating-point number.

Return type:

BitArray

classmethod from_signed_int(value, length)[source]

Converts a signed integer to a bit array using off-set binary representation.

Parameters:
  • value (int) – The signed integer to convert.

  • length (int) – The length of the resulting bit array.

Returns:

A BitArray representing the bits of the signed integer.

Return type:

BitArray

Raises:

AssertionError – If the value is out of range for the specified length.

classmethod zeros(length)[source]

Creates a BitArray filled with zeros.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with False values.

Return type:

BitArray

classmethod ones(length)[source]

Creates a BitArray filled with ones.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with True values.

Return type:

BitArray

classmethod parse_bitarray(bitstring)[source]

Parses a string of bits (with optional spaces) into a BitArray instance. Non-valid characters are ignored.

Parameters:

bitstring (Iterable[str]) – A string of bits, e.g., “1010 1100”.

Returns:

A BitArray instance created from the bit string.

Return type:

BitArray

to_float()[source]

Converts a 64-bit array to a floating-point number.

Returns:

The floating-point number represented by the bit array.

Return type:

float

Raises:

AssertionError – If the bit array is not 64 bits long.

to_int()[source]

Converts the bit array to an unsigned integer.

Returns:

The integer represented by the bit array.

Return type:

int

to_signed_int()[source]

Converts a bit array into a signed integer using off-set binary representation.

Returns:

The signed integer represented by the bit array.

Return type:

int

Raises:

AssertionError – If the bit array is empty.

shift(shift_amount, fill=False)[source]

Shifts the bit array left or right by a specified number of bits.

This function shifts the bits in the array, filling in new bits with the specified fill value. If the value is positive, it shifts left; if negative, it shifts right. Fills the new bits with the specified fill value (default is False).

Parameters:
  • shift_amount (int) – The number of bits to shift. Positive for left shift, negative for right shift.

  • fill (bool, optional) – The value to fill in the new bits created by the shift. Defaults to False.

Returns:

A new BitArray with the bits shifted and filled.

Return type:

BitArray

copy()[source]

Creates a copy of the bit array.

Returns:

A new BitArray with the same bits.

Return type:

BitArray

__len__()[source]

Returns the length of the bit array.

Returns:

The number of bits in the array.

Return type:

int

__getitem__(index: int) bool[source]
__getitem__(index: slice) BitArray

Get a bit or a slice of bits as a new BitArray.

__setitem__(index: int, value: bool) None[source]
__setitem__(index: slice, value: 'BitArray' | list[bool]) None

Sets an item or slice in the bit array.

Parameters:
  • index (int or slice) – The index or slice to set.

  • value (bool or list[bool] or BitArray) – The value(s) to assign.

__iter__()[source]

Iterates over the bits in the array.

Yields:

bool – The next bit in the array.

__add__(other)[source]

Concatenates two bit arrays.

Parameters:

other (BitArray or list[bool]) – The other bit array or list to concatenate.

Returns:

The concatenated bit array.

Return type:

BitArray

__radd__(other)[source]

Reverse concatenation with a list.

Parameters:

other (list[bool]) – The list to concatenate before this bit array.

Returns:

The concatenated bit array.

Return type:

BitArray

__eq__(other)[source]

Checks equality with another BitArray or list.

Parameters:

other (object) – The object to compare with.

Returns:

True if equal, False otherwise.

Return type:

bool

__bool__()[source]

Returns True if any bit is set.

Returns:

True if any bit is set, False otherwise.

Return type:

bool

__repr__()[source]

Returns a string representation of the BitArray.

Returns:

String representation of the BitArray.

Return type:

str

__str__()[source]

Returns a string representation of the bits.

Returns:

String representation of the bits.

Return type:

str

__init__(*args, **kwargs)
any()[source]

Returns True if any bit is set to True.

Returns:

True if any bit is set to True, False otherwise.

Return type:

bool

all()[source]

Returns True if all bits are set to True.

Returns:

True if all bits are set to True, False otherwise.

Return type:

bool

count(value=True)[source]

Counts the number of bits set to the specified value.

Parameters:

value (bool, optional) – The value to count. Defaults to True.

Returns:

The number of bits set to the specified value.

Return type:

int

reverse()[source]

Returns a new BitArray with the bits in reverse order.

Returns:

A new BitArray with the bits in reverse order.

Return type:

BitArray

Implementations

ListBoolBitArray

class flexfloat.ListBoolBitArray(bits=None)[source]

Bases: BitArrayCommonMixin

A bit array class that encapsulates a list of booleans with utility methods.

This implementation uses a list of boolean values to represent the bits, allowing for dynamic resizing and easy manipulation of individual bits.

__init__(bits=None)[source]

Initializes a ListBoolBitArray.

Parameters:

bits (list[bool] | None, optional) – Initial list of boolean values. Defaults to empty list.

classmethod from_bits(bits=None)[source]

Creates a BitArray from a list of boolean values.

Parameters:

bits (list[bool] | None, optional) – List of boolean values. Defaults to None, which creates an empty BitArray.

Returns:

A BitArray created from the bits.

Return type:

ListBoolBitArray

classmethod zeros(length)[source]

Creates a BitArray filled with zeros.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with False values.

Return type:

ListBoolBitArray

classmethod ones(length)[source]

Creates a BitArray filled with ones.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with True values.

Return type:

ListBoolBitArray

to_int()[source]

Converts the bit array to an unsigned integer (LSB-first).

Returns:

The integer represented by the bit array.

Return type:

int

copy()[source]

Creates a copy of the bit array.

Returns:

A new BitArray with the same bits.

Return type:

ListBoolBitArray

to_float()[source]

Converts a 64-bit array to a floating-point number (LSB-first).

Returns:

The floating-point number represented by the bit array.

Return type:

float

Raises:

AssertionError – If the bit array is not 64 bits long.

__len__()[source]

Returns the length of the bit array.

Returns:

The number of bits in the array.

Return type:

int

__getitem__(index: int) bool[source]
__getitem__(index: slice) ListBoolBitArray

Get a bit or a slice of bits as a new ListBoolBitArray.

__setitem__(index: int, value: bool) None[source]
__setitem__(index: slice, value: BitArray | list[bool]) None

Sets an item or slice in the bit array.

Parameters:
  • index (int or slice) – The index or slice to set.

  • value (bool or list[bool] or BitArray) – The value(s) to assign.

Raises:

TypeError – If value type does not match index type.

__iter__()[source]

Iterates over the bits in the array.

Yields:

bool – The next bit in the array.

__add__(other)[source]

Concatenates two bit arrays.

Parameters:

other (BitArray or list[bool]) – The other bit array or list to concatenate.

Returns:

The concatenated bit array.

Return type:

ListBoolBitArray

__radd__(other)[source]

Reverse concatenation with a list.

Parameters:

other (list[bool]) – The list to concatenate before this bit array.

Returns:

The concatenated bit array.

Return type:

ListBoolBitArray

__repr__()[source]

Returns a string representation of the BitArray.

Returns:

String representation of the BitArray.

Return type:

str

ListInt64BitArray

class flexfloat.ListInt64BitArray(chunks=None, length=0)[source]

Bases: BitArrayCommonMixin

A memory-efficient bit array class using a list of int64 values.

This implementation packs 64 bits per integer, making it more memory efficient for large bit arrays compared to the boolean list implementation.

__init__(chunks=None, length=0)[source]

Initializes a ListInt64BitArray.

Parameters:
  • chunks (list[int] | None, optional) – Initial list of int64 chunks. Defaults to empty list.

  • length (int, optional) – The amount of bits in the array. Defaults to 0.

Raises:

ValueError – If length is negative.

classmethod from_bits(bits=None)[source]

Creates a BitArray from a list of boolean values.

Parameters:

bits (list[bool] | None, optional) – List of boolean values in LSB-first order. Defaults to None, which creates an empty BitArray.

Returns:

A BitArray created from the bits.

Return type:

ListInt64BitArray

classmethod zeros(length)[source]

Creates a BitArray filled with zeros.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with False values.

Return type:

ListInt64BitArray

classmethod ones(length)[source]

Creates a BitArray filled with ones.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with True values.

Return type:

ListInt64BitArray

to_int()[source]

Converts the bit array to an unsigned integer (LSB-first).

Returns:

The integer represented by the bit array.

Return type:

int

to_float()[source]

Converts a 64-bit array to a floating-point number (LSB-first).

Returns:

The floating-point number represented by the bit array.

Return type:

float

Raises:

AssertionError – If the bit array is not 64 bits long.

copy()[source]

Creates a copy of the bit array.

Returns:

A new BitArray with the same bits.

Return type:

ListInt64BitArray

__len__()[source]

Returns the length of the bit array.

Returns:

The number of bits in the array.

Return type:

int

__getitem__(index: int) bool[source]
__getitem__(index: slice) ListInt64BitArray

Get a bit or a slice of bits as a new ListInt64BitArray.

__setitem__(index: int, value: bool) None[source]
__setitem__(index: slice, value: BitArray | list[bool]) None

Sets an item or slice in the bit array.

Parameters:
  • index (int or slice) – The index or slice to set.

  • value (bool or list[bool] or BitArray) – The value(s) to assign.

Raises:
  • TypeError – If value type does not match index type.

  • ValueError – If value length does not match slice length.

__iter__()[source]

Iterates over the bits in the array.

Yields:

bool – The next bit in the array.

__add__(other)[source]

Concatenates two bit arrays.

Parameters:

other (BitArray or list[bool]) – The other bit array or list to concatenate.

Returns:

The concatenated bit array.

Return type:

ListInt64BitArray

__radd__(other)[source]

Reverse concatenation with a list.

Parameters:

other (list[bool]) – The list to concatenate before this bit array.

Returns:

The concatenated bit array.

Return type:

ListInt64BitArray

__eq__(other)[source]

Checks equality with another BitArray or list.

Parameters:

other (object) – The object to compare with.

Returns:

True if equal, False otherwise.

Return type:

bool

__bool__()[source]

Returns True if any bit is set.

Returns:

True if any bit is set, False otherwise.

Return type:

bool

__repr__()[source]

Returns a string representation of the BitArray.

Returns:

String representation of the BitArray.

Return type:

str

any()[source]

Returns True if any bit is set to True.

Returns:

True if any bit is set to True, False otherwise.

Return type:

bool

all()[source]

Returns True if all bits are set to True.

Returns:

True if all bits are set to True, False otherwise.

Return type:

bool

BigIntBitArray

class flexfloat.BigIntBitArray(value=0, length=0)[source]

Bases: BitArrayCommonMixin

A memory-efficient bit array class using Python’s infinite-size int.

This implementation stores all bits as a single Python integer, leveraging Python’s arbitrary precision arithmetic for potentially unlimited size. Since Python integers are arbitrary precision, this can handle bit arrays of any size limited only by available memory.

__init__(value=0, length=0)[source]

Initializes a BigIntBitArray.

Parameters:
  • value (int, optional) – Initial integer value representing the bits. Defaults to 0.

  • length (int, optional) – The number of bits in the array. Defaults to 0.

Raises:

ValueError – If length is negative.

classmethod from_bits(bits=None)[source]

Creates a BitArray from a list of boolean values.

Parameters:

bits (list[bool] | None, optional) – List of boolean values. Defaults to None, which creates an empty BitArray.

Returns:

A BitArray created from the bits.

Return type:

BigIntBitArray

classmethod zeros(length)[source]

Creates a BitArray filled with zeros.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with False values.

Return type:

BigIntBitArray

classmethod ones(length)[source]

Creates a BitArray filled with ones.

Parameters:

length (int) – The length of the bit array.

Returns:

A BitArray filled with True values.

Return type:

BigIntBitArray

to_float()[source]

Converts a 64-bit array to a floating-point number (LSB-first).

Returns:

The floating-point number represented by the bit array.

Return type:

float

Raises:

AssertionError – If the bit array is not 64 bits long.

to_int()[source]

Converts the bit array to an unsigned integer (LSB-first).

Returns:

The integer represented by the bit array.

Return type:

int

copy()[source]

Creates a copy of the bit array.

Returns:

A new BitArray with the same bits.

Return type:

BigIntBitArray

__len__()[source]

Returns the length of the bit array.

Returns:

The number of bits in the array.

Return type:

int

__getitem__(index: int) bool[source]
__getitem__(index: slice) BigIntBitArray

Gets an item or slice from the bit array.

Parameters:

index (int or slice) – The index or slice to retrieve.

Returns:

The bit value or a new BitArray for the slice.

Return type:

bool or BigIntBitArray

__setitem__(index: int, value: bool) None[source]
__setitem__(index: slice, value: BitArray | list[bool]) None

Sets an item or slice in the bit array.

Parameters:
  • index (int or slice) – The index or slice to set.

  • value (bool or list[bool] or BitArray) – The value(s) to assign.

Raises:
  • TypeError – If value type does not match index type.

  • ValueError – If value length does not match slice length.

__iter__()[source]

Iterates over the bits in the array.

Yields:

bool – The next bit in the array.

__add__(other)[source]

Concatenates two bit arrays.

Parameters:

other (BitArray or list[bool]) – The other bit array or list to concatenate.

Returns:

The concatenated bit array.

Return type:

BigIntBitArray

Raises:

TypeError – If other is not iterable.

__radd__(other)[source]

Reverse concatenation with a list.

Parameters:

other (list[bool]) – The list to concatenate before this bit array.

Returns:

The concatenated bit array.

Return type:

BigIntBitArray

Raises:

TypeError – If other is not iterable.

__repr__()[source]

Returns a string representation of the BitArray.

Returns:

String representation of the BitArray.

Return type:

str

Usage Examples

Choosing a BitArray Implementation

from flexfloat import FlexFloat, ListBoolBitArray, ListInt64BitArray, BigIntBitArray

# Use different implementations
FlexFloat.set_bitarray_implementation(ListBoolBitArray)
FlexFloat.set_bitarray_implementation(ListInt64BitArray)
FlexFloat.set_bitarray_implementation(BigIntBitArray)

Performance Characteristics

BitArray Performance Comparison

Implementation

Memory Usage

Speed

Best Use Case

ListBoolBitArray

High

Slow

Debugging, small numbers

ListInt64BitArray

Medium

Fast

General purpose

BigIntBitArray

Low

Very Fast

Large numbers, production

Direct BitArray Usage

from flexfloat import ListInt64BitArray

# Create a BitArray
bits = ListInt64BitArray([0], length=8)  # 8-bit array

# Set individual bits
bits[0] = True
bits[7] = True

# Get bits
print(bits[0])  # True
print(bits[1])  # False

# Convert to integer
value = bits.to_int()
print(value)    # 129

# Create from integer
bits2 = ListInt64BitArray.from_signed_int(128, 8)
print(bits2.to_int())  # 255

BitArray Operations

from flexfloat import ListInt64BitArray

# Create BitArrays
a = ListInt64BitArray.from_signed_int(12, 4)  # 1100
b = ListInt64BitArray.from_signed_int(10, 4)  # 1010

# Bitwise operations (if implemented)
and_result = a & b    # 1000 = 8
or_result = a | b     # 1110 = 14
xor_result = a ^ b    # 0110 = 6
not_result = ~a       # 0011 = 3

Extending BitArrays

from flexfloat import ListInt64BitArray

# Start with small BitArray
bits = ListInt64BitArray.from_signed_int(5, 4)  # 0101
print(len(bits))  # 4

# Extend it (if implemented)
extended = bits.extend(8)
print(len(extended))  # 8
print(extended.to_int())  # Still 5, but with more bits

Custom BitArray Implementation

You can create your own BitArray implementation by following the protocol:

from flexfloat.bitarray import BitArray
from typing import Iterator

class CustomBitArray(BitArray):
    def __init__(self, length: int):
        self._data = [False] * length
    def __len__(self) -> int:
        return len(self._data)
    def __getitem__(self, index: int) -> bool:
        return self._data[index]
    def __setitem__(self, index: int, value: bool) -> None:
        self._data[index] = value
    def __iter__(self) -> Iterator[bool]:
        return iter(self._data)
    def to_int(self) -> int:
        result = 0
        for i, bit in enumerate(self._data):
            if bit:
                result |= (1 << i)
        return result
    @classmethod
    def from_signed_int(cls, value: int, length: int) -> 'CustomBitArray':
        bits = cls(length)
        for i in range(length):
            bits[i] = bool(value & (1 << i))
        return bits