METADATA 33 KB

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