Efficient arrays of booleans with comprehensive sequence operations, bitwise operations, and specialized functionality for encoding/decoding variable-length prefix codes.
npx @tessl/cli install tessl/pypi-bitarray@3.7.00
# Bitarray
1
2
Bitarray provides an efficient object type for representing arrays of booleans. Bitarrays behave like Python lists but store data as packed bits, using one byte for every eight bits. The library offers comprehensive sequence operations, bitwise operations, and specialized functionality for encoding/decoding variable-length prefix codes, with all core operations implemented in C for maximum performance.
3
4
## Package Information
5
6
- **Package Name**: bitarray
7
- **Package Type**: pypi
8
- **Language**: Python (with C extensions)
9
- **Installation**: `pip install bitarray`
10
11
## Core Imports
12
13
```python
14
from bitarray import bitarray, frozenbitarray, decodetree, bits2bytes, get_default_endian, test
15
```
16
17
For utility functions:
18
19
```python
20
from bitarray.util import zeros, ones, ba2hex, hex2ba, ba2int, int2ba
21
```
22
23
## Basic Usage
24
25
```python
26
from bitarray import bitarray
27
from bitarray.util import zeros, ones, ba2hex
28
29
# Create bitarrays
30
a = bitarray('1010110') # From string
31
b = bitarray([1, 0, 1, 0]) # From list
32
c = zeros(8) # All zeros
33
d = ones(5) # All ones
34
35
# Basic operations
36
print(len(a)) # 7
37
print(a[2]) # 1
38
a.append(1) # Add bit
39
a.extend('01') # Add multiple bits
40
41
# Bitwise operations
42
result = a & b # AND
43
result = a | b # OR
44
result = a ^ b # XOR
45
result = ~a # NOT
46
result = a << 2 # Left shift
47
result = a >> 1 # Right shift
48
49
# Conversions
50
hex_str = ba2hex(a) # To hexadecimal
51
bytes_data = a.tobytes() # To bytes
52
int_val = a.count() # Count set bits
53
54
# Search operations
55
pos = a.find(bitarray('10')) # Find subsequence
56
all_pos = list(a.search(bitarray('1'))) # Find all occurrences
57
58
# Immutable version
59
frozen = frozenbitarray(a) # Hashable, immutable
60
```
61
62
## Architecture
63
64
Bitarray's design centers around efficient bit manipulation and storage:
65
66
- **Core bitarray class**: Sequence-like interface with comprehensive bit operations
67
- **C implementation**: Core operations implemented in C for maximum performance
68
- **Buffer protocol**: Zero-copy integration with NumPy and memory-mapped files
69
- **Endianness support**: Little-endian and big-endian bit representations
70
- **Utility module**: Extended functionality for specific use cases
71
- **Immutable variant**: frozenbitarray for hashable bit sequences
72
73
The library supports both individual bit operations and bulk operations on bit sequences, with optimized algorithms for common patterns like searching, counting, and bitwise arithmetic.
74
75
## Capabilities
76
77
### Core Operations
78
79
Fundamental bitarray operations including creation, modification, sequence operations, and bitwise arithmetic. These form the foundation for all bit manipulation tasks.
80
81
```python { .api }
82
class bitarray:
83
def __init__(self, initializer=0, /, endian='big', buffer=None) -> None: ...
84
def append(self, value: int) -> None: ...
85
def extend(self, x: Union[str, Iterable[int]]) -> None: ...
86
def count(self, sub_bitarray=1, start=0, stop=None, step=1) -> int: ...
87
def find(self, sub_bitarray, start=0, stop=None, right=False) -> int: ...
88
def search(self, sub_bitarray, start=0, stop=None, right=False) -> Iterator[int]: ...
89
90
# Properties
91
@property
92
def endian(self) -> str: ...
93
@property
94
def nbytes(self) -> int: ...
95
@property
96
def readonly(self) -> bool: ...
97
```
98
99
[Core Operations](./core-operations.md)
100
101
### Creation and Conversion
102
103
Comprehensive methods for creating bitarrays from various sources and converting to different formats including integers, hex strings, bytes, and other representations.
104
105
```python { .api }
106
# Core conversion methods
107
def tobytes(self) -> bytes: ...
108
def tolist(self) -> list[int]: ...
109
def to01(self, group=0, sep='') -> str: ...
110
def frombytes(self, a: bytes) -> None: ...
111
112
# Utility functions
113
def zeros(length: int, endian: Optional[str] = None) -> bitarray: ...
114
def ones(length: int, endian: Optional[str] = None) -> bitarray: ...
115
def ba2int(a: bitarray, signed: bool = False) -> int: ...
116
def int2ba(i: int, length: Optional[int] = None, endian: Optional[str] = None, signed: bool = False) -> bitarray: ...
117
def ba2hex(a: bitarray, group: int = 0, sep: str = '') -> str: ...
118
def hex2ba(s: str, endian: Optional[str] = None) -> bitarray: ...
119
```
120
121
[Creation and Conversion](./creation-conversion.md)
122
123
### Utility Functions
124
125
Extended functionality from the bitarray.util module including random generation, analysis functions, pretty printing, compression, and specialized bit manipulation operations.
126
127
```python { .api }
128
def urandom(length: int, endian: Optional[str] = None) -> bitarray: ...
129
def count_n(a: bitarray, n: int, value: int = 1) -> int: ...
130
def parity(a: bitarray) -> int: ...
131
def count_and(a: bitarray, b: bitarray) -> int: ...
132
def subset(a: bitarray, b: bitarray) -> bool: ...
133
def serialize(a: bitarray) -> bytes: ...
134
def deserialize(b: bytes) -> bitarray: ...
135
```
136
137
[Utility Functions](./utility-functions.md)
138
139
### Advanced Features
140
141
Specialized functionality for encoding/decoding variable-length prefix codes, Huffman coding, compression algorithms, and advanced bit manipulation techniques.
142
143
```python { .api }
144
def encode(self, code: dict, iterable) -> None: ...
145
def decode(self, code: Union[dict, decodetree]) -> Iterator: ...
146
147
class decodetree:
148
def __init__(self, code: dict) -> None: ...
149
def complete(self) -> bool: ...
150
def nodes(self) -> int: ...
151
152
def huffman_code(freq_map: dict, endian: Optional[str] = None) -> dict: ...
153
def vl_encode(a: bitarray) -> bytes: ...
154
def vl_decode(stream: Iterable[int], endian: Optional[str] = None) -> bitarray: ...
155
```
156
157
[Advanced Features](./advanced-features.md)
158
159
## Types
160
161
```python { .api }
162
from typing import Union, Optional, Iterable, Iterator, Any, NamedTuple
163
from collections.abc import Sequence
164
from unittest.runner import TextTestResult
165
166
# Type aliases
167
BytesLike = Union[bytes, bytearray]
168
CodeDict = dict[Any, bitarray]
169
170
class BufferInfo(NamedTuple):
171
address: int
172
nbytes: int
173
endian: str
174
padbits: int
175
alloc: int
176
readonly: bool
177
imported: bool
178
exports: int
179
180
class frozenbitarray(bitarray):
181
def __hash__(self) -> int: ...
182
```