0
# Core Operations
1
2
Core bitarray operations including creation, modification, sequence operations, and bitwise arithmetic. These operations form the foundation for all bit manipulation tasks.
3
4
## Capabilities
5
6
### Bitarray Construction
7
8
Creates bitarray objects from various initializers with configurable bit-endianness and optional buffer support.
9
10
```python { .api }
11
class bitarray:
12
"""Efficient array of booleans stored as packed bits"""
13
def __init__(self,
14
initializer: Union[int, str, Iterable[int], None] = 0,
15
endian: Union[str, None] = 'big',
16
buffer: Any = None) -> None:
17
"""
18
Create a bitarray object.
19
20
Args:
21
initializer: Initial value - int (length), str ('01' format), iterable of ints, or bitarray
22
endian: Bit-endianness - 'big' or 'little'
23
buffer: Buffer object for memory mapping
24
"""
25
```
26
27
**Usage Examples:**
28
29
```python
30
from bitarray import bitarray
31
32
# Different initialization methods
33
a = bitarray(8) # 8 zero bits
34
b = bitarray('10110') # From binary string
35
c = bitarray([1, 0, 1, 1, 0]) # From list
36
d = bitarray(c) # Copy constructor
37
e = bitarray(8, 'little') # Little-endian
38
```
39
40
### Sequence Operations
41
42
Standard sequence operations including appending, extending, inserting, removing, and accessing elements.
43
44
```python { .api }
45
def append(self, value: int) -> None:
46
"""Append single bit (0 or 1) to end of bitarray"""
47
48
def extend(self, x: Union[str, Iterable[int]]) -> None:
49
"""Extend bitarray with bits from string or iterable"""
50
51
def insert(self, i: int, value: int) -> None:
52
"""Insert bit at position i"""
53
54
def pop(self, i: int = -1) -> int:
55
"""Remove and return bit at position i (default last)"""
56
57
def remove(self, value: int) -> None:
58
"""Remove first occurrence of bit value"""
59
60
def clear(self) -> None:
61
"""Remove all bits"""
62
63
def copy(self) -> bitarray:
64
"""Return shallow copy"""
65
66
def reverse(self) -> None:
67
"""Reverse bitarray in-place"""
68
69
def sort(self, reverse: int = 0) -> None:
70
"""
71
Sort bits in-place.
72
73
Args:
74
reverse: Sort order - 0 for ascending (0s first), 1 for descending (1s first)
75
"""
76
```
77
78
**Usage Examples:**
79
80
```python
81
a = bitarray('101')
82
a.append(1) # '1011'
83
a.extend('00') # '101100'
84
a.insert(2, 1) # '1011100'
85
bit = a.pop() # Returns 0, a becomes '101110'
86
a.remove(0) # Remove first 0: '11110'
87
a.reverse() # '01111'
88
```
89
90
### Search and Analysis
91
92
Functions for searching bit patterns and analyzing bitarray contents.
93
94
```python { .api }
95
def count(self,
96
sub_bitarray: Union[bitarray, int] = 1,
97
start: int = 0,
98
stop: Optional[int] = None,
99
step: int = 1) -> int:
100
"""Count occurrences of sub_bitarray in slice"""
101
102
def find(self,
103
sub_bitarray: Union[bitarray, int],
104
start: int = 0,
105
stop: Optional[int] = None,
106
right: bool = False) -> int:
107
"""Find first occurrence, return -1 if not found"""
108
109
def index(self,
110
sub_bitarray: Union[bitarray, int],
111
start: int = 0,
112
stop: Optional[int] = None,
113
right: bool = False) -> int:
114
"""Find first occurrence, raise ValueError if not found"""
115
116
def search(self,
117
sub_bitarray: Union[bitarray, int],
118
start: int = 0,
119
stop: Optional[int] = None,
120
right: bool = False) -> Iterator[int]:
121
"""Return iterator of all occurrence positions"""
122
123
def all(self) -> bool:
124
"""True if all bits are 1 (or bitarray is empty)"""
125
126
def any(self) -> bool:
127
"""True if any bit is 1"""
128
```
129
130
**Usage Examples:**
131
132
```python
133
a = bitarray('110101101')
134
135
# Counting
136
print(a.count()) # 6 (count of 1s)
137
print(a.count(0)) # 3 (count of 0s)
138
print(a.count('10')) # 2 (count of '10' pattern)
139
140
# Searching
141
pos = a.find('101') # 2 (first occurrence)
142
pos = a.find('111') # -1 (not found)
143
positions = list(a.search('1')) # [0, 1, 3, 5, 6, 8]
144
145
# Boolean tests
146
print(a.all()) # False
147
print(a.any()) # True
148
```
149
150
### Bit Manipulation
151
152
Direct bit manipulation operations including inversion, filling, and setting all bits.
153
154
```python { .api }
155
def invert(self, i: Optional[int] = None) -> None:
156
"""Invert all bits, or bit at position i if specified"""
157
158
def setall(self, value: int) -> None:
159
"""Set all bits to value (0 or 1)"""
160
161
def fill(self) -> int:
162
"""Fill unused bits in last byte with 0, return number filled"""
163
164
def bytereverse(self, start: int = 0, stop: Optional[int] = None) -> None:
165
"""Reverse bit order within each byte"""
166
```
167
168
**Usage Examples:**
169
170
```python
171
a = bitarray('10110')
172
173
# Bit manipulation
174
a.invert() # '01001'
175
a.invert(2) # '01101' (invert bit at position 2)
176
a.setall(1) # '11111'
177
a.setall(0) # '00000'
178
179
# Byte operations
180
a = bitarray('1011001010110')
181
a.bytereverse() # Reverse bits within bytes
182
```
183
184
### Magic Methods and Operators
185
186
Comprehensive operator support for arithmetic, comparison, and bitwise operations.
187
188
```python { .api }
189
# Sequence protocol
190
def __len__(self) -> int: ...
191
def __iter__(self) -> Iterator[int]: ...
192
def __getitem__(self, key: Union[int, slice]) -> Union[int, bitarray]: ...
193
def __setitem__(self, key: Union[int, slice], value: Union[int, bitarray]) -> None: ...
194
def __delitem__(self, key: Union[int, slice]) -> None: ...
195
def __contains__(self, item: Union[int, bitarray]) -> bool: ...
196
197
# Arithmetic operations
198
def __add__(self, other: bitarray) -> bitarray: ...
199
def __iadd__(self, other: bitarray) -> bitarray: ...
200
def __mul__(self, n: int) -> bitarray: ...
201
def __imul__(self, n: int) -> bitarray: ...
202
def __rmul__(self, n: int) -> bitarray: ...
203
204
# Bitwise operations
205
def __and__(self, other: bitarray) -> bitarray: ...
206
def __or__(self, other: bitarray) -> bitarray: ...
207
def __xor__(self, other: bitarray) -> bitarray: ...
208
def __invert__(self) -> bitarray: ...
209
def __lshift__(self, n: int) -> bitarray: ...
210
def __rshift__(self, n: int) -> bitarray: ...
211
212
# In-place bitwise operations
213
def __iand__(self, other: bitarray) -> bitarray: ...
214
def __ior__(self, other: bitarray) -> bitarray: ...
215
def __ixor__(self, other: bitarray) -> bitarray: ...
216
def __ilshift__(self, n: int) -> bitarray: ...
217
def __irshift__(self, n: int) -> bitarray: ...
218
219
# Comparison operations
220
def __eq__(self, other: bitarray) -> bool: ...
221
def __ne__(self, other: bitarray) -> bool: ...
222
def __lt__(self, other: bitarray) -> bool: ...
223
def __le__(self, other: bitarray) -> bool: ...
224
def __gt__(self, other: bitarray) -> bool: ...
225
def __ge__(self, other: bitarray) -> bool: ...
226
```
227
228
**Usage Examples:**
229
230
```python
231
a = bitarray('1010')
232
b = bitarray('1100')
233
234
# Sequence operations
235
print(len(a)) # 4
236
print(a[1]) # 0
237
print(a[1:3]) # bitarray('01')
238
a[1] = 1 # a becomes '1110'
239
240
# Arithmetic
241
c = a + b # '11101100' (concatenation)
242
c = a * 3 # '111011101110' (repetition)
243
a += b # In-place concatenation
244
245
# Bitwise operations
246
result = a & b # AND: '1100'
247
result = a | b # OR: '1110'
248
result = a ^ b # XOR: '0010'
249
result = ~a # NOT: '0001'
250
result = a << 2 # Left shift: '101000'
251
result = a >> 1 # Right shift: '010'
252
253
# In-place bitwise
254
a &= b # In-place AND
255
a |= b # In-place OR
256
a ^= b # In-place XOR
257
a <<= 2 # In-place left shift
258
a >>= 1 # In-place right shift
259
```
260
261
### Properties
262
263
Bitarray properties providing metadata about the object's state and configuration.
264
265
```python { .api }
266
@property
267
def endian(self) -> str:
268
"""Bit-endianness: 'big' or 'little'"""
269
270
@property
271
def nbytes(self) -> int:
272
"""Number of bytes used to store bitarray"""
273
274
@property
275
def padbits(self) -> int:
276
"""Number of padding bits in last byte"""
277
278
@property
279
def readonly(self) -> bool:
280
"""True if bitarray is read-only"""
281
```
282
283
**Usage Examples:**
284
285
```python
286
a = bitarray('1010110', 'little')
287
288
print(a.endian) # 'little'
289
print(a.nbytes) # 1 (7 bits = 1 byte)
290
print(a.padbits) # 1 (8-7 = 1 padding bit)
291
print(a.readonly) # False
292
293
# Buffer info for advanced use
294
info = a.buffer_info()
295
print(f"Address: {info.address}")
296
print(f"Bytes: {info.nbytes}")
297
print(f"Endian: {info.endian}")
298
```
299
300
## Memory and Buffer Operations
301
302
Advanced memory management and buffer protocol support for integration with NumPy and other libraries.
303
304
```python { .api }
305
def buffer_info(self) -> BufferInfo:
306
"""Return named tuple with buffer information"""
307
308
def __buffer__(self, flags: int, /) -> memoryview:
309
"""Return memoryview for buffer protocol"""
310
311
def __release_buffer__(self, buffer: memoryview, /) -> None:
312
"""Release buffer"""
313
314
def _freeze(self) -> None:
315
"""Make bitarray immutable (internal method used by frozenbitarray)"""
316
```
317
318
The bitarray class supports Python's buffer protocol, enabling zero-copy operations with NumPy arrays, memory-mapped files, and other buffer-aware objects.