bitarray 3.8.0__cp314-cp314t-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,992 @@
1
+ Metadata-Version: 2.4
2
+ Name: bitarray
3
+ Version: 3.8.0
4
+ Summary: efficient arrays of booleans -- C extension
5
+ Home-page: https://github.com/ilanschnell/bitarray
6
+ Author: Ilan Schnell
7
+ Author-email: ilanschnell@gmail.com
8
+ License: PSF-2.0
9
+ Classifier: Development Status :: 6 - Mature
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: C
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.6
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: Free Threading :: 1 - Unstable
24
+ Classifier: Topic :: Utilities
25
+ License-File: LICENSE
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: home-page
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: summary
34
+
35
+ bitarray: efficient arrays of booleans
36
+ ======================================
37
+
38
+ This library provides an object type which efficiently represents an array
39
+ of booleans. Bitarrays are sequence types and behave very much like usual
40
+ lists. Eight bits are represented by one byte in a contiguous block of
41
+ memory. The user can select between two representations: little-endian
42
+ and big-endian. All functionality is implemented in C.
43
+ Methods for accessing the machine representation are provided, including the
44
+ ability to import and export buffers. This allows creating bitarrays that
45
+ are mapped to other objects, including memory-mapped files.
46
+
47
+
48
+ Key features
49
+ ------------
50
+
51
+ * The bit-endianness can be specified for each bitarray object, see below.
52
+ * Sequence methods: slicing (including slice assignment and deletion),
53
+ operations ``+``, ``*``, ``+=``, ``*=``, the ``in`` operator, ``len()``
54
+ * Bitwise operations: ``~``, ``&``, ``|``, ``^``, ``<<``, ``>>`` (as well as
55
+ their in-place versions ``&=``, ``|=``, ``^=``, ``<<=``, ``>>=``).
56
+ * Fast methods for encoding and decoding variable bit length prefix codes.
57
+ * Bitarray objects support the buffer protocol (both importing and
58
+ exporting buffers).
59
+ * Packing and unpacking to other binary data formats, e.g. ``numpy.ndarray``.
60
+ * Pickling and unpickling of bitarray objects.
61
+ * Immutable ``frozenbitarray`` objects which are hashable
62
+ * Sequential search
63
+ * Type hinting
64
+ * Extensive test suite with about 600 unittests
65
+ * Utility module ``bitarray.util``:
66
+
67
+ * conversion to and from hexadecimal strings
68
+ * generating random bitarrays
69
+ * pretty printing
70
+ * conversion to and from integers
71
+ * creating Huffman codes
72
+ * compression of sparse bitarrays
73
+ * (de-) serialization
74
+ * various count functions
75
+ * other helpful functions
76
+
77
+
78
+ Installation
79
+ ------------
80
+
81
+ Python wheels are are available on PyPI for all major platforms and Python
82
+ versions. Which means you can simply:
83
+
84
+ .. code-block:: shell-session
85
+
86
+ $ pip install bitarray
87
+
88
+ Once you have installed the package, you may want to test it:
89
+
90
+ .. code-block:: shell-session
91
+
92
+ $ python -c 'import bitarray; bitarray.test()'
93
+ bitarray is installed in: /Users/ilan/bitarray/bitarray
94
+ bitarray version: 3.8.0
95
+ sys.version: 3.13.5 (main, Jun 16 2025) [Clang 18.1.8]
96
+ sys.prefix: /Users/ilan/miniforge
97
+ pointer size: 64 bit
98
+ sizeof(size_t): 8
99
+ sizeof(bitarrayobject): 80
100
+ HAVE_BUILTIN_BSWAP64: 1
101
+ default bit-endianness: big
102
+ machine byte-order: little
103
+ Py_GIL_DISABLED: 0
104
+ Py_DEBUG: 0
105
+ DEBUG: 0
106
+ .........................................................................
107
+ .........................................................................
108
+ ................................................................
109
+ ----------------------------------------------------------------------
110
+ Ran 595 tests in 0.165s
111
+
112
+ OK
113
+
114
+ The ``test()`` function is part of the API. It will return
115
+ a ``unittest.runner.TextTestResult`` object, such that one can verify that
116
+ all tests ran successfully by:
117
+
118
+ .. code-block:: python
119
+
120
+ import bitarray
121
+ assert bitarray.test().wasSuccessful()
122
+
123
+
124
+ Usage
125
+ -----
126
+
127
+ As mentioned above, bitarray objects behave very much like lists, so
128
+ there is not too much to learn. The biggest difference from list
129
+ objects (except that bitarray are obviously homogeneous) is the ability
130
+ to access the machine representation of the object.
131
+ When doing so, the bit-endianness is of importance; this issue is
132
+ explained in detail in the section below. Here, we demonstrate the
133
+ basic usage of bitarray objects:
134
+
135
+ .. code-block:: python
136
+
137
+ >>> from bitarray import bitarray
138
+ >>> a = bitarray() # create empty bitarray
139
+ >>> a.append(1)
140
+ >>> a.extend([1, 0])
141
+ >>> a
142
+ bitarray('110')
143
+ >>> x = bitarray(2 ** 20) # bitarray of length 1048576 (initialized to 0)
144
+ >>> len(x)
145
+ 1048576
146
+ >>> bitarray('1001 011') # initialize from string (whitespace is ignored)
147
+ bitarray('1001011')
148
+ >>> lst = [1, 0, False, True, True]
149
+ >>> a = bitarray(lst) # initialize from iterable
150
+ >>> a
151
+ bitarray('10011')
152
+ >>> a[2] # indexing a single item will always return an integer
153
+ 0
154
+ >>> a[2:4] # whereas indexing a slice will always return a bitarray
155
+ bitarray('01')
156
+ >>> a[2:3] # even when the slice length is just one
157
+ bitarray('0')
158
+ >>> a.count(1)
159
+ 3
160
+ >>> a.remove(0) # removes first occurrence of 0
161
+ >>> a
162
+ bitarray('1011')
163
+
164
+ Like lists, bitarray objects support slice assignment and deletion:
165
+
166
+ .. code-block:: python
167
+
168
+ >>> a = bitarray(50)
169
+ >>> a.setall(0) # set all elements in a to 0
170
+ >>> a[11:37:3] = 9 * bitarray('1')
171
+ >>> a
172
+ bitarray('00000000000100100100100100100100100100000000000000')
173
+ >>> del a[12::3]
174
+ >>> a
175
+ bitarray('0000000000010101010101010101000000000')
176
+ >>> a[-6:] = bitarray('10011')
177
+ >>> a
178
+ bitarray('000000000001010101010101010100010011')
179
+ >>> a += bitarray('000111')
180
+ >>> a[9:]
181
+ bitarray('001010101010101010100010011000111')
182
+
183
+ In addition, slices can be assigned to booleans, which is easier (and
184
+ faster) than assigning to a bitarray in which all values are the same:
185
+
186
+ .. code-block:: python
187
+
188
+ >>> a = 20 * bitarray('0')
189
+ >>> a[1:15:3] = True
190
+ >>> a
191
+ bitarray('01001001001001000000')
192
+
193
+ This is easier and faster than:
194
+
195
+ .. code-block:: python
196
+
197
+ >>> a = 20 * bitarray('0')
198
+ >>> a[1:15:3] = 5 * bitarray('1')
199
+ >>> a
200
+ bitarray('01001001001001000000')
201
+
202
+ Note that in the latter we have to create a temporary bitarray whose length
203
+ must be known or calculated. Another example of assigning slices to Booleans,
204
+ is setting ranges:
205
+
206
+ .. code-block:: python
207
+
208
+ >>> a = bitarray(30)
209
+ >>> a[:] = 0 # set all elements to 0 - equivalent to a.setall(0)
210
+ >>> a[10:25] = 1 # set elements in range(10, 25) to 1
211
+ >>> a
212
+ bitarray('000000000011111111111111100000')
213
+
214
+ As of bitarray version 2.8, indices may also be lists of arbitrary
215
+ indices (like in NumPy), or bitarrays that are treated as masks,
216
+ see `Bitarray indexing <https://github.com/ilanschnell/bitarray/blob/master/doc/indexing.rst>`__.
217
+
218
+
219
+ Bitwise operators
220
+ -----------------
221
+
222
+ Bitarray objects support the bitwise operators ``~``, ``&``, ``|``, ``^``,
223
+ ``<<``, ``>>`` (as well as their in-place versions ``&=``, ``|=``, ``^=``,
224
+ ``<<=``, ``>>=``). The behavior is very much what one would expect:
225
+
226
+ .. code-block:: python
227
+
228
+ >>> a = bitarray('101110001')
229
+ >>> ~a # invert
230
+ bitarray('010001110')
231
+ >>> b = bitarray('111001011')
232
+ >>> a ^ b # bitwise XOR
233
+ bitarray('010111010')
234
+ >>> a &= b # inplace AND
235
+ >>> a
236
+ bitarray('101000001')
237
+ >>> a <<= 2 # in-place left-shift by 2
238
+ >>> a
239
+ bitarray('100000100')
240
+ >>> b >> 1 # return b right-shifted by 1
241
+ bitarray('011100101')
242
+
243
+ The C language does not specify the behavior of negative shifts and
244
+ of left shifts larger or equal than the width of the promoted left operand.
245
+ The exact behavior is compiler/machine specific.
246
+ This Python bitarray library specifies the behavior as follows:
247
+
248
+ * the length of the bitarray is never changed by any shift operation
249
+ * blanks are filled by 0
250
+ * negative shifts raise ``ValueError``
251
+ * shifts larger or equal to the length of the bitarray result in
252
+ bitarrays with all values 0
253
+
254
+ It is worth noting that (regardless of bit-endianness) the bitarray left
255
+ shift (``<<``) always shifts towards lower indices, and the right
256
+ shift (``>>``) always shifts towards higher indices.
257
+
258
+
259
+ Bit-endianness
260
+ --------------
261
+
262
+ For many purposes the bit-endianness is not of any relevance to the end user
263
+ and can be regarded as an implementation detail of bitarray objects.
264
+ However, there are use cases when the bit-endianness becomes important.
265
+ These use cases involve explicitly reading and writing the bitarray buffer
266
+ using ``.tobytes()``, ``.frombytes()``, ``.tofile()`` or ``.fromfile()``,
267
+ importing and exporting buffers. Also, a number of utility functions
268
+ in ``bitarray.util`` will return different results depending on
269
+ bit-endianness, such as ``ba2hex()`` or ``ba2int``.
270
+ To better understand this topic, please read `bit-endianness <https://github.com/ilanschnell/bitarray/blob/master/doc/endianness.rst>`__.
271
+
272
+
273
+ Buffer protocol
274
+ ---------------
275
+
276
+ Bitarray objects support the buffer protocol. They can both export their
277
+ own buffer, as well as import another object's buffer. To learn more about
278
+ this topic, please read `buffer protocol <https://github.com/ilanschnell/bitarray/blob/master/doc/buffer.rst>`__. There is also an example that shows how
279
+ to memory-map a file to a bitarray: `mmapped-file.py <https://github.com/ilanschnell/bitarray/blob/master/examples/mmapped-file.py>`__
280
+
281
+
282
+ Variable bit length prefix codes
283
+ --------------------------------
284
+
285
+ The ``.encode()`` method takes a dictionary mapping symbols to bitarrays
286
+ and an iterable, and extends the bitarray object with the encoded symbols
287
+ found while iterating. For example:
288
+
289
+ .. code-block:: python
290
+
291
+ >>> d = {'H':bitarray('111'), 'e':bitarray('0'),
292
+ ... 'l':bitarray('110'), 'o':bitarray('10')}
293
+ ...
294
+ >>> a = bitarray()
295
+ >>> a.encode(d, 'Hello')
296
+ >>> a
297
+ bitarray('111011011010')
298
+
299
+ Note that the string ``'Hello'`` is an iterable, but the symbols are not
300
+ limited to characters, in fact any immutable Python object can be a symbol.
301
+ Taking the same dictionary, we can apply the ``.decode()`` method which will
302
+ return an iterable of the symbols:
303
+
304
+ .. code-block:: python
305
+
306
+ >>> list(a.decode(d))
307
+ ['H', 'e', 'l', 'l', 'o']
308
+ >>> ''.join(a.decode(d))
309
+ 'Hello'
310
+
311
+ Symbols are not limited to being characters.
312
+ The above dictionary ``d`` can be efficiently constructed using the function
313
+ ``bitarray.util.huffman_code()``. I also wrote `Huffman coding in Python
314
+ using bitarray <http://ilan.schnell-web.net/prog/huffman/>`__ for more
315
+ background information.
316
+
317
+ When the codes are large, and you have many decode calls, most time will
318
+ be spent creating the (same) internal decode tree objects. In this case,
319
+ it will be much faster to create a ``decodetree`` object, which can be
320
+ passed to bitarray's ``.decode()`` method, instead of passing the prefix
321
+ code dictionary to those methods itself:
322
+
323
+ .. code-block:: python
324
+
325
+ >>> from bitarray import bitarray, decodetree
326
+ >>> t = decodetree({'a': bitarray('0'), 'b': bitarray('1')})
327
+ >>> a = bitarray('0110')
328
+ >>> list(a.decode(t))
329
+ ['a', 'b', 'b', 'a']
330
+
331
+ The sole purpose of the immutable ``decodetree`` object is to be passed
332
+ to bitarray's ``.decode()`` method.
333
+
334
+
335
+ Frozenbitarrays
336
+ ---------------
337
+
338
+ A ``frozenbitarray`` object is very similar to the bitarray object.
339
+ The difference is that this a ``frozenbitarray`` is immutable, and hashable,
340
+ and can therefore be used as a dictionary key:
341
+
342
+ .. code-block:: python
343
+
344
+ >>> from bitarray import frozenbitarray
345
+ >>> key = frozenbitarray('1100011')
346
+ >>> {key: 'some value'}
347
+ {frozenbitarray('1100011'): 'some value'}
348
+ >>> key[3] = 1
349
+ Traceback (most recent call last):
350
+ ...
351
+ TypeError: frozenbitarray is immutable
352
+
353
+
354
+ Reference
355
+ =========
356
+
357
+ bitarray version: 3.8.0 -- `change log <https://github.com/ilanschnell/bitarray/blob/master/doc/changelog.rst>`__
358
+
359
+ In the following, ``item`` and ``value`` are usually a single bit -
360
+ an integer 0 or 1.
361
+
362
+ Also, ``sub_bitarray`` refers to either a bitarray, or an ``item``.
363
+
364
+
365
+ The bitarray object:
366
+ --------------------
367
+
368
+ ``bitarray(initializer=0, /, endian='big', buffer=None)`` -> bitarray
369
+ Return a new bitarray object whose items are bits initialized from
370
+ the optional initializer, and bit-endianness.
371
+ The initializer may be one of the following types:
372
+ a.) ``int`` bitarray, initialized to zeros, of given length
373
+ b.) ``bytes`` or ``bytearray`` to initialize buffer directly
374
+ c.) ``str`` of 0s and 1s, ignoring whitespace and "_"
375
+ d.) iterable of integers 0 or 1.
376
+
377
+ Optional keyword arguments:
378
+
379
+ ``endian``: Specifies the bit-endianness of the created bitarray object.
380
+ Allowed values are ``big`` and ``little`` (the default is ``big``).
381
+ The bit-endianness effects the buffer representation of the bitarray.
382
+
383
+ ``buffer``: Any object which exposes a buffer. When provided, ``initializer``
384
+ cannot be present (or has to be ``None``). The imported buffer may be
385
+ read-only or writable, depending on the object type.
386
+
387
+ New in version 2.3: optional ``buffer`` argument
388
+
389
+ New in version 3.4: allow initializer ``bytes`` or ``bytearray`` to set buffer directly
390
+
391
+
392
+ bitarray methods:
393
+ -----------------
394
+
395
+ ``all()`` -> bool
396
+ Return ``True`` when all bits in bitarray are 1.
397
+ ``a.all()`` is a faster version of ``all(a)``.
398
+
399
+
400
+ ``any()`` -> bool
401
+ Return ``True`` when any bit in bitarray is 1.
402
+ ``a.any()`` is a faster version of ``any(a)``.
403
+
404
+
405
+ ``append(item, /)``
406
+ Append ``item`` to the end of the bitarray.
407
+
408
+
409
+ ``buffer_info()`` -> BufferInfo
410
+ Return named tuple with following fields:
411
+
412
+ 0. ``address``: memory address of buffer
413
+ 1. ``nbytes``: buffer size (in bytes)
414
+ 2. ``endian``: bit-endianness as a string
415
+ 3. ``padbits``: number of pad bits
416
+ 4. ``alloc``: allocated memory for buffer (in bytes)
417
+ 5. ``readonly``: memory is read-only (bool)
418
+ 6. ``imported``: buffer is imported (bool)
419
+ 7. ``exports``: number of buffer exports
420
+
421
+ New in version 3.7: return named tuple
422
+
423
+
424
+ ``bytereverse(start=0, stop=<end of buffer>, /)``
425
+ For each byte in byte-range(``start``, ``stop``) reverse bits in-place.
426
+ The start and stop indices are given in terms of bytes (not bits).
427
+ Also note that this method only changes the buffer; it does not change the
428
+ bit-endianness of the bitarray object. Pad bits are left unchanged such
429
+ that two consecutive calls will always leave the bitarray unchanged.
430
+
431
+ New in version 2.2.5: optional start and stop arguments
432
+
433
+
434
+ ``clear()``
435
+ Remove all items from bitarray.
436
+
437
+ New in version 1.4
438
+
439
+
440
+ ``copy()`` -> bitarray
441
+ Return copy of bitarray (with same bit-endianness).
442
+
443
+
444
+ ``count(value=1, start=0, stop=<end>, step=1, /)`` -> int
445
+ Number of occurrences of ``value`` bitarray within ``[start:stop:step]``.
446
+ Optional arguments ``start``, ``stop`` and ``step`` are interpreted in
447
+ slice notation, meaning ``a.count(value, start, stop, step)`` equals
448
+ ``a[start:stop:step].count(value)``.
449
+ The ``value`` may also be a sub-bitarray. In this case non-overlapping
450
+ occurrences are counted within ``[start:stop]`` (``step`` must be 1).
451
+
452
+ New in version 1.1.0: optional start and stop arguments
453
+
454
+ New in version 2.3.7: optional step argument
455
+
456
+ New in version 2.9: add non-overlapping sub-bitarray count
457
+
458
+
459
+ ``decode(code, /)`` -> iterator
460
+ Given a prefix code (a dict mapping symbols to bitarrays, or ``decodetree``
461
+ object), decode content of bitarray and return an iterator over
462
+ corresponding symbols.
463
+
464
+ See also: `Bitarray 3 transition <https://github.com/ilanschnell/bitarray/blob/master/doc/bitarray3.rst>`__
465
+
466
+ New in version 3.0: returns iterator (equivalent to past ``.iterdecode()``)
467
+
468
+
469
+ ``encode(code, iterable, /)``
470
+ Given a prefix code (a dict mapping symbols to bitarrays),
471
+ iterate over the iterable object with symbols, and extend bitarray
472
+ with corresponding bitarray for each symbol.
473
+
474
+
475
+ ``extend(iterable, /)``
476
+ Append items from to the end of the bitarray.
477
+ If ``iterable`` is a (Unicode) string, each ``0`` and ``1`` are appended as
478
+ bits (ignoring whitespace and underscore).
479
+
480
+ New in version 3.4: allow ``bytes`` object
481
+
482
+
483
+ ``fill()`` -> int
484
+ Add zeros to the end of the bitarray, such that the length will be
485
+ a multiple of 8, and return the number of bits added [0..7].
486
+
487
+
488
+ ``find(sub_bitarray, start=0, stop=<end>, /, right=False)`` -> int
489
+ Return lowest (or rightmost when ``right=True``) index where sub_bitarray
490
+ is found, such that sub_bitarray is contained within ``[start:stop]``.
491
+ Return -1 when sub_bitarray is not found.
492
+
493
+ New in version 2.1
494
+
495
+ New in version 2.9: add optional keyword argument ``right``
496
+
497
+
498
+ ``frombytes(bytes, /)``
499
+ Extend bitarray with raw bytes from a bytes-like object.
500
+ Each added byte will add eight bits to the bitarray.
501
+
502
+ New in version 2.5.0: allow bytes-like argument
503
+
504
+
505
+ ``fromfile(f, n=-1, /)``
506
+ Extend bitarray with up to ``n`` bytes read from file object ``f`` (or any
507
+ other binary stream what supports a ``.read()`` method, e.g. ``io.BytesIO``).
508
+ Each read byte will add eight bits to the bitarray. When ``n`` is omitted
509
+ or negative, reads and extends all data until EOF.
510
+ When ``n`` is non-negative but exceeds the available data, ``EOFError`` is
511
+ raised. However, the available data is still read and extended.
512
+
513
+
514
+ ``index(sub_bitarray, start=0, stop=<end>, /, right=False)`` -> int
515
+ Return lowest (or rightmost when ``right=True``) index where sub_bitarray
516
+ is found, such that sub_bitarray is contained within ``[start:stop]``.
517
+ Raises ``ValueError`` when sub_bitarray is not present.
518
+
519
+ New in version 2.9: add optional keyword argument ``right``
520
+
521
+
522
+ ``insert(index, value, /)``
523
+ Insert ``value`` into bitarray before ``index``.
524
+
525
+
526
+ ``invert(index=<all bits>, /)``
527
+ Invert all bits in bitarray (in-place).
528
+ When the optional ``index`` is given, only invert the single bit at ``index``.
529
+
530
+ New in version 1.5.3: optional index argument
531
+
532
+
533
+ ``pack(bytes, /)``
534
+ Extend bitarray from a bytes-like object, where each byte corresponds
535
+ to a single bit. The byte ``b'\x00'`` maps to bit 0 and all other bytes
536
+ map to bit 1.
537
+
538
+ This method, as well as the ``.unpack()`` method, are meant for efficient
539
+ transfer of data between bitarray objects to other Python objects (for
540
+ example NumPy's ndarray object) which have a different memory view.
541
+
542
+ New in version 2.5.0: allow bytes-like argument
543
+
544
+
545
+ ``pop(index=-1, /)`` -> item
546
+ Remove and return item at ``index`` (default last).
547
+ Raises ``IndexError`` if index is out of range.
548
+
549
+
550
+ ``remove(value, /)``
551
+ Remove the first occurrence of ``value``.
552
+ Raises ``ValueError`` if value is not present.
553
+
554
+
555
+ ``reverse()``
556
+ Reverse all bits in bitarray (in-place).
557
+
558
+
559
+ ``search(sub_bitarray, start=0, stop=<end>, /, right=False)`` -> iterator
560
+ Return iterator over indices where sub_bitarray is found, such that
561
+ sub_bitarray is contained within ``[start:stop]``.
562
+ The indices are iterated in ascending order (from lowest to highest),
563
+ unless ``right=True``, which will iterate in descending order (starting with
564
+ rightmost match).
565
+
566
+ See also: `Bitarray 3 transition <https://github.com/ilanschnell/bitarray/blob/master/doc/bitarray3.rst>`__
567
+
568
+ New in version 2.9: optional start and stop arguments - add optional keyword argument ``right``
569
+
570
+ New in version 3.0: returns iterator (equivalent to past ``.itersearch()``)
571
+
572
+
573
+ ``setall(value, /)``
574
+ Set all elements in bitarray to ``value``.
575
+ Note that ``a.setall(value)`` is equivalent to ``a[:] = value``.
576
+
577
+
578
+ ``sort(reverse=False)``
579
+ Sort all bits in bitarray (in-place).
580
+
581
+
582
+ ``to01(group=0, sep=' ')`` -> str
583
+ Return bitarray as (Unicode) string of ``0``s and ``1``s.
584
+ The bits are grouped into ``group`` bits (default is no grouping).
585
+ When grouped, the string ``sep`` is inserted between groups
586
+ of ``group`` characters, default is a space.
587
+
588
+ New in version 3.3: optional ``group`` and ``sep`` arguments
589
+
590
+
591
+ ``tobytes()`` -> bytes
592
+ Return the bitarray buffer (pad bits are set to zero).
593
+ ``a.tobytes()`` is equivalent to ``bytes(a)``
594
+
595
+
596
+ ``tofile(f, /)``
597
+ Write bitarray buffer to file object ``f``.
598
+
599
+
600
+ ``tolist()`` -> list
601
+ Return bitarray as list of integers.
602
+ ``a.tolist()`` equals ``list(a)``.
603
+
604
+ Note that the list object being created will require 32 or 64 times more
605
+ memory (depending on the machine architecture) than the bitarray object,
606
+ which may cause a memory error if the bitarray is very large.
607
+
608
+
609
+ ``unpack(zero=b'\x00', one=b'\x01')`` -> bytes
610
+ Return bytes that contain one byte for each bit in the bitarray,
611
+ using specified mapping.
612
+
613
+
614
+ bitarray data descriptors:
615
+ --------------------------
616
+
617
+ Data descriptors were added in version 2.6.
618
+
619
+ ``endian`` -> str
620
+ bit-endianness as Unicode string
621
+
622
+ New in version 3.4: replaces former ``.endian()`` method
623
+
624
+
625
+ ``nbytes`` -> int
626
+ buffer size in bytes
627
+
628
+
629
+ ``padbits`` -> int
630
+ number of pad bits
631
+
632
+
633
+ ``readonly`` -> bool
634
+ bool indicating whether buffer is read-only
635
+
636
+
637
+ Other objects:
638
+ --------------
639
+
640
+ ``frozenbitarray(initializer=0, /, endian='big', buffer=None)`` -> frozenbitarray
641
+ Return a ``frozenbitarray`` object. Initialized the same way a ``bitarray``
642
+ object is initialized. A ``frozenbitarray`` is immutable and hashable,
643
+ and may therefore be used as a dictionary key.
644
+
645
+ New in version 1.1
646
+
647
+
648
+ ``decodetree(code, /)`` -> decodetree
649
+ Given a prefix code (a dict mapping symbols to bitarrays),
650
+ create a binary tree object to be passed to ``.decode()``.
651
+
652
+ New in version 1.6
653
+
654
+
655
+ Functions defined in the `bitarray` module:
656
+ -------------------------------------------
657
+
658
+ ``bits2bytes(n, /)`` -> int
659
+ Return the number of bytes necessary to store n bits.
660
+
661
+
662
+ ``get_default_endian()`` -> str
663
+ Return the default bit-endianness for new bitarray objects being created.
664
+
665
+ New in version 1.3
666
+
667
+
668
+ ``test(verbosity=1)`` -> TextTestResult
669
+ Run self-test, and return ``unittest.runner.TextTestResult`` object.
670
+
671
+
672
+ Functions defined in `bitarray.util` module:
673
+ --------------------------------------------
674
+
675
+ This sub-module was added in version 1.2.
676
+
677
+ ``any_and(a, b, /)`` -> bool
678
+ Efficient implementation of ``any(a & b)``.
679
+
680
+ New in version 2.7
681
+
682
+
683
+ ``ba2base(n, bitarray, /, group=0, sep=' ')`` -> str
684
+ Return a string containing the base ``n`` ASCII representation of
685
+ the bitarray. Allowed values for ``n`` are 2, 4, 8, 16, 32 and 64.
686
+ The bitarray has to be multiple of length 1, 2, 3, 4, 5 or 6 respectively.
687
+ For ``n=32`` the RFC 4648 Base32 alphabet is used, and for ``n=64`` the
688
+ standard base 64 alphabet is used.
689
+ When grouped, the string ``sep`` is inserted between groups
690
+ of ``group`` characters, default is a space.
691
+
692
+ See also: `Bitarray representations <https://github.com/ilanschnell/bitarray/blob/master/doc/represent.rst>`__
693
+
694
+ New in version 1.9
695
+
696
+ New in version 3.3: optional ``group`` and ``sep`` arguments
697
+
698
+
699
+ ``ba2hex(bitarray, /, group=0, sep=' ')`` -> hexstr
700
+ Return a string containing the hexadecimal representation of
701
+ the bitarray (which has to be multiple of 4 in length).
702
+ When grouped, the string ``sep`` is inserted between groups
703
+ of ``group`` characters, default is a space.
704
+
705
+ New in version 3.3: optional ``group`` and ``sep`` arguments
706
+
707
+
708
+ ``ba2int(bitarray, /, signed=False)`` -> int
709
+ Convert the given bitarray to an integer.
710
+ The bit-endianness of the bitarray is respected.
711
+ ``signed`` indicates whether two's complement is used to represent the integer.
712
+
713
+
714
+ ``base2ba(n, asciistr, /, endian=None)`` -> bitarray
715
+ Bitarray of base ``n`` ASCII representation.
716
+ Allowed values for ``n`` are 2, 4, 8, 16, 32 and 64.
717
+ For ``n=32`` the RFC 4648 Base32 alphabet is used, and for ``n=64`` the
718
+ standard base 64 alphabet is used. Whitespace is ignored.
719
+
720
+ See also: `Bitarray representations <https://github.com/ilanschnell/bitarray/blob/master/doc/represent.rst>`__
721
+
722
+ New in version 1.9
723
+
724
+ New in version 3.3: ignore whitespace
725
+
726
+
727
+ ``byteswap(a, n=<buffer size>, /)``
728
+ Reverse every ``n`` consecutive bytes of ``a`` in-place.
729
+ By default, all bytes are reversed. Note that ``n`` is not limited to 2, 4
730
+ or 8, but can be any positive integer.
731
+ Also, ``a`` may be any object that exposes a writable buffer.
732
+ Nothing about this function is specific to bitarray objects.
733
+
734
+ We should mention that Python's ``array.array`` object has a
735
+ method ``.byteswap()`` with similar functionality. However, unlike
736
+ bitarray's ``util.byteswap()`` function, this method is limited to
737
+ swapping 2, 4, or 8 consecutive bytes.
738
+
739
+ New in version 3.4
740
+
741
+
742
+ ``canonical_decode(bitarray, count, symbol, /)`` -> iterator
743
+ Decode bitarray using canonical Huffman decoding tables
744
+ where ``count`` is a sequence containing the number of symbols of each length
745
+ and ``symbol`` is a sequence of symbols in canonical order.
746
+
747
+ See also: `Canonical Huffman Coding <https://github.com/ilanschnell/bitarray/blob/master/doc/canonical.rst>`__
748
+
749
+ New in version 2.5
750
+
751
+
752
+ ``canonical_huffman(dict, /)`` -> tuple
753
+ Given a frequency map, a dictionary mapping symbols to their frequency,
754
+ calculate the canonical Huffman code. Returns a tuple containing:
755
+
756
+ 0. the canonical Huffman code as a dict mapping symbols to bitarrays
757
+ 1. a list containing the number of symbols of each code length
758
+ 2. a list of symbols in canonical order
759
+
760
+ Note: the two lists may be used as input for ``canonical_decode()``.
761
+
762
+ See also: `Canonical Huffman Coding <https://github.com/ilanschnell/bitarray/blob/master/doc/canonical.rst>`__
763
+
764
+ New in version 2.5
765
+
766
+
767
+ ``correspond_all(a, b, /)`` -> tuple
768
+ Return tuple with counts of: ~a & ~b, ~a & b, a & ~b, a & b
769
+
770
+ New in version 3.4
771
+
772
+
773
+ ``count_and(a, b, /)`` -> int
774
+ Return ``(a & b).count()`` in a memory efficient manner,
775
+ as no intermediate bitarray object gets created.
776
+
777
+
778
+ ``count_n(a, n, value=1, /)`` -> int
779
+ Return lowest index ``i`` for which ``a[:i].count(value) == n``.
780
+ Raises ``ValueError`` when ``n`` exceeds total count (``a.count(value)``).
781
+
782
+ New in version 2.3.6: optional value argument
783
+
784
+
785
+ ``count_or(a, b, /)`` -> int
786
+ Return ``(a | b).count()`` in a memory efficient manner,
787
+ as no intermediate bitarray object gets created.
788
+
789
+
790
+ ``count_xor(a, b, /)`` -> int
791
+ Return ``(a ^ b).count()`` in a memory efficient manner,
792
+ as no intermediate bitarray object gets created.
793
+
794
+ This is also known as the Hamming distance.
795
+
796
+
797
+ ``deserialize(bytes, /)`` -> bitarray
798
+ Return a bitarray given a bytes-like representation such as returned
799
+ by ``serialize()``.
800
+
801
+ See also: `Bitarray representations <https://github.com/ilanschnell/bitarray/blob/master/doc/represent.rst>`__
802
+
803
+ New in version 1.8
804
+
805
+ New in version 2.5.0: allow bytes-like argument
806
+
807
+
808
+ ``gen_primes(n, /, endian=None, odd=False)`` -> bitarray
809
+ Generate a bitarray of length ``n`` in which active indices are prime numbers.
810
+ By default (``odd=False``), active indices correspond to prime numbers directly.
811
+ When ``odd=True``, only odd prime numbers are represented in the resulting
812
+ bitarray ``a``, and ``a[i]`` corresponds to ``2*i+1`` being prime or not.
813
+
814
+ Apart from working with prime numbers, this function is useful for
815
+ testing, as it provides a simple way to create a well-defined bitarray
816
+ of any length.
817
+
818
+ New in version 3.7
819
+
820
+
821
+ ``hex2ba(hexstr, /, endian=None)`` -> bitarray
822
+ Bitarray of hexadecimal representation. hexstr may contain any number
823
+ (including odd numbers) of hex digits (upper or lower case).
824
+ Whitespace is ignored.
825
+
826
+ New in version 3.3: ignore whitespace
827
+
828
+
829
+ ``huffman_code(dict, /, endian=None)`` -> dict
830
+ Given a frequency map, a dictionary mapping symbols to their frequency,
831
+ calculate the Huffman code, i.e. a dict mapping those symbols to
832
+ bitarrays (with given bit-endianness). Note that the symbols are not limited
833
+ to being strings. Symbols may be any hashable object.
834
+
835
+
836
+ ``int2ba(int, /, length=None, endian=None, signed=False)`` -> bitarray
837
+ Convert the given integer to a bitarray (with given bit-endianness,
838
+ and no leading (big-endian) / trailing (little-endian) zeros), unless
839
+ the ``length`` of the bitarray is provided. An ``OverflowError`` is raised
840
+ if the integer is not representable with the given number of bits.
841
+ ``signed`` determines whether two's complement is used to represent the integer,
842
+ and requires ``length`` to be provided.
843
+
844
+
845
+ ``intervals(bitarray, /)`` -> iterator
846
+ Compute all uninterrupted intervals of 1s and 0s, and return an
847
+ iterator over tuples ``(value, start, stop)``. The intervals are guaranteed
848
+ to be in order, and their size is always non-zero (``stop - start > 0``).
849
+
850
+ New in version 2.7
851
+
852
+
853
+ ``ones(n, /, endian=None)`` -> bitarray
854
+ Create a bitarray of length ``n``, with all values ``1``, and optional
855
+ bit-endianness (``little`` or ``big``).
856
+
857
+ New in version 2.9
858
+
859
+
860
+ ``parity(a, /)`` -> int
861
+ Return parity of bitarray ``a``.
862
+ ``parity(a)`` is equivalent to ``a.count() % 2`` but more efficient.
863
+
864
+ New in version 1.9
865
+
866
+
867
+ ``pprint(bitarray, /, stream=None, group=8, indent=4, width=80)``
868
+ Pretty-print bitarray object to ``stream``, defaults is ``sys.stdout``.
869
+ By default, bits are grouped in bytes (8 bits), and 64 bits per line.
870
+ Non-bitarray objects are printed using ``pprint.pprint()``.
871
+
872
+ New in version 1.8
873
+
874
+
875
+ ``random_k(n, /, k, endian=None)`` -> bitarray
876
+ Return (pseudo-) random bitarray of length ``n`` with ``k`` elements
877
+ set to one. Mathematically equivalent to setting (in a bitarray of
878
+ length ``n``) all bits at indices ``random.sample(range(n), k)`` to one.
879
+ The random bitarrays are reproducible when giving Python's ``random.seed()``
880
+ a specific seed value.
881
+
882
+ New in version 3.6
883
+
884
+
885
+ ``random_p(n, /, p=0.5, endian=None)`` -> bitarray
886
+ Return (pseudo-) random bitarray of length ``n``, where each bit has
887
+ probability ``p`` of being one (independent of any other bits). Mathematically
888
+ equivalent to ``bitarray((random() < p for _ in range(n)), endian)``, but much
889
+ faster for large ``n``. The random bitarrays are reproducible when giving
890
+ Python's ``random.seed()`` with a specific seed value.
891
+
892
+ This function requires Python 3.12 or higher, as it depends on the standard
893
+ library function ``random.binomialvariate()``. Raises ``NotImplementedError``
894
+ when Python version is too low.
895
+
896
+ See also: `Random Bitarrays <https://github.com/ilanschnell/bitarray/blob/master/doc/random_p.rst>`__
897
+
898
+ New in version 3.5
899
+
900
+
901
+ ``sc_decode(stream, /)`` -> bitarray
902
+ Decompress binary stream (an integer iterator, or bytes-like object) of a
903
+ sparse compressed (``sc``) bitarray, and return the decoded bitarray.
904
+ This function consumes only one bitarray and leaves the remaining stream
905
+ untouched. Use ``sc_encode()`` for compressing (encoding).
906
+
907
+ See also: `Compression of sparse bitarrays <https://github.com/ilanschnell/bitarray/blob/master/doc/sparse_compression.rst>`__
908
+
909
+ New in version 2.7
910
+
911
+
912
+ ``sc_encode(bitarray, /)`` -> bytes
913
+ Compress a sparse bitarray and return its binary representation.
914
+ This representation is useful for efficiently storing sparse bitarrays.
915
+ Use ``sc_decode()`` for decompressing (decoding).
916
+
917
+ See also: `Compression of sparse bitarrays <https://github.com/ilanschnell/bitarray/blob/master/doc/sparse_compression.rst>`__
918
+
919
+ New in version 2.7
920
+
921
+
922
+ ``serialize(bitarray, /)`` -> bytes
923
+ Return a serialized representation of the bitarray, which may be passed to
924
+ ``deserialize()``. It efficiently represents the bitarray object (including
925
+ its bit-endianness) and is guaranteed not to change in future releases.
926
+
927
+ See also: `Bitarray representations <https://github.com/ilanschnell/bitarray/blob/master/doc/represent.rst>`__
928
+
929
+ New in version 1.8
930
+
931
+
932
+ ``strip(bitarray, /, mode='right')`` -> bitarray
933
+ Return a new bitarray with zeros stripped from left, right or both ends.
934
+ Allowed values for mode are the strings: ``left``, ``right``, ``both``
935
+
936
+
937
+ ``subset(a, b, /)`` -> bool
938
+ Return ``True`` if bitarray ``a`` is a subset of bitarray ``b``.
939
+ ``subset(a, b)`` is equivalent to ``a | b == b`` (and equally ``a & b == a``) but
940
+ more efficient as no intermediate bitarray object is created and the buffer
941
+ iteration is stopped as soon as one mismatch is found.
942
+
943
+
944
+ ``sum_indices(a, /, mode=1)`` -> int
945
+ Return sum of indices of all active bits in bitarray ``a``.
946
+ Equivalent to ``sum(i for i, v in enumerate(a) if v)``.
947
+ ``mode=2`` sums square of indices.
948
+
949
+ New in version 3.6
950
+
951
+ New in version 3.7: add optional mode argument
952
+
953
+
954
+ ``urandom(n, /, endian=None)`` -> bitarray
955
+ Return random bitarray of length ``n`` (uses ``os.urandom()``).
956
+
957
+ New in version 1.7
958
+
959
+
960
+ ``vl_decode(stream, /, endian=None)`` -> bitarray
961
+ Decode binary stream (an integer iterator, or bytes-like object), and
962
+ return the decoded bitarray. This function consumes only one bitarray and
963
+ leaves the remaining stream untouched. Use ``vl_encode()`` for encoding.
964
+
965
+ See also: `Variable length bitarray format <https://github.com/ilanschnell/bitarray/blob/master/doc/variable_length.rst>`__
966
+
967
+ New in version 2.2
968
+
969
+
970
+ ``vl_encode(bitarray, /)`` -> bytes
971
+ Return variable length binary representation of bitarray.
972
+ This representation is useful for efficiently storing small bitarray
973
+ in a binary stream. Use ``vl_decode()`` for decoding.
974
+
975
+ See also: `Variable length bitarray format <https://github.com/ilanschnell/bitarray/blob/master/doc/variable_length.rst>`__
976
+
977
+ New in version 2.2
978
+
979
+
980
+ ``xor_indices(a, /)`` -> int
981
+ Return xor reduced indices of all active bits in bitarray ``a``.
982
+ This is essentially equivalent to
983
+ ``reduce(operator.xor, (i for i, v in enumerate(a) if v))``.
984
+
985
+ New in version 3.2
986
+
987
+
988
+ ``zeros(n, /, endian=None)`` -> bitarray
989
+ Create a bitarray of length ``n``, with all values ``0``, and optional
990
+ bit-endianness (``little`` or ``big``).
991
+
992
+