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:
- classmethod from_float(value)[source]
Converts a floating-point number to a bit array.
- classmethod from_signed_int(value, length)[source]
Converts a signed integer to a bit array using off-set binary representation.
- Parameters:
- Returns:
A BitArray representing the bits of the signed integer.
- Return type:
- Raises:
AssertionError – If the value is out of range for the specified length.
- classmethod zeros(length)[source]
Creates a BitArray filled with zeros.
- classmethod ones(length)[source]
Creates a BitArray filled with ones.
- 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:
- 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:
- 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:
- 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:
- 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).
- copy()[source]
Creates a copy of the bit array.
- Returns:
A new BitArray with the same bits.
- Return type:
- __len__()[source]
Returns the length of the bit array.
- Returns:
The number of bits in the array.
- Return type:
- __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.
- __add__(other)[source]
Concatenates two bit arrays.
- __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:
- __eq__(other)[source]
Checks equality with another BitArray or list.
- __bool__()[source]
Returns True if any bit is set.
- Returns:
True if any bit is set, False otherwise.
- Return type:
- __repr__()[source]
Returns a string representation of the BitArray.
- Returns:
String representation of the BitArray.
- Return type:
- __str__()[source]
Returns a string representation of the bits.
- Returns:
String representation of the bits.
- Return type:
- __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:
- all()[source]
Returns True if all bits are set to True.
- Returns:
True if all bits are set to True, False otherwise.
- Return type:
- count(value=True)[source]
Counts the number of bits set to the specified value.
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:
- 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:
- 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:
- to_int()[source]
Converts the bit array to an unsigned integer (LSB-first).
- Returns:
The integer represented by the bit array.
- Return type:
- copy()[source]
Creates a copy of the bit array.
- Returns:
A new BitArray with the same bits.
- Return type:
- 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:
- 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:
- __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.
- __add__(other)[source]
Concatenates two bit arrays.
- Parameters:
other (
BitArray
orlist[bool]
) – The other bit array or list to concatenate.- Returns:
The concatenated bit array.
- Return type:
- __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
- 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:
- 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:
- 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:
- to_int()[source]
Converts the bit array to an unsigned integer (LSB-first).
- Returns:
The integer represented by the bit array.
- Return type:
- 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:
- 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:
- __len__()[source]
Returns the length of the bit array.
- Returns:
The number of bits in the array.
- Return type:
- __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.
- __add__(other)[source]
Concatenates two bit arrays.
- Parameters:
other (
BitArray
orlist[bool]
) – The other bit array or list to concatenate.- Returns:
The concatenated bit array.
- Return type:
- __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:
- __eq__(other)[source]
Checks equality with another BitArray or list.
- __bool__()[source]
Returns True if any bit is set.
- Returns:
True if any bit is set, False otherwise.
- Return type:
- __repr__()[source]
Returns a string representation of the BitArray.
- Returns:
String representation of the BitArray.
- Return type:
- any()[source]
Returns True if any bit is set to True.
- Returns:
True if any bit is set to True, False otherwise.
- Return type:
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:
- 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:
- 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:
- 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:
- 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:
- 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:
- copy()[source]
Creates a copy of the bit array.
- Returns:
A new BitArray with the same bits.
- Return type:
- __len__()[source]
Returns the length of the bit array.
- Returns:
The number of bits in the array.
- Return type:
- __getitem__(index: int) bool [source]
- __getitem__(index: slice) BigIntBitArray
Gets an item or slice from the bit array.
- Parameters:
- Returns:
The bit value or a new BitArray for the slice.
- Return type:
- __setitem__(index: int, value: bool) None [source]
- __setitem__(index: slice, value: BitArray | list[bool]) None
Sets an item or slice in the bit array.
- __add__(other)[source]
Concatenates two bit arrays.
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
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