### Install bitarray Package Source: https://pypi.org/project/bitarray Use pip to install the bitarray package. Python wheels are available for all major platforms and Python versions. ```bash pip install bitarray ``` -------------------------------- ### Run Tests Source: https://pypi.org/project/bitarray The test() function is part of the API and can be used to verify the installation and integrity of the bitarray library. It returns a unittest.runner.TextTestResult object. ```APIDOC import bitarray # Run all tests and get the result object test_result = bitarray.test() # Verify if all tests were successful assert test_result.wasSuccessful() ``` -------------------------------- ### Run bitarray Tests Source: https://pypi.org/project/bitarray Execute the built-in test suite for the bitarray package to verify its installation and functionality. The test() function returns a unittest.runner.TextTestResult object. ```python import bitarray bitarray.test() ``` ```python import bitarray assert bitarray.test().wasSuccessful() ``` -------------------------------- ### Basic Bitarray Operations Source: https://pypi.org/project/bitarray Demonstrates creating, appending, extending, and initializing bitarrays from strings or iterables. Shows how to access elements and slices, and use methods like count and remove. ```python >>> from bitarray import bitarray >>> a = bitarray() # create empty bitarray >>> a.append(1) >>> a.extend([1, 0]) >>> a bitarray('110') >>> x = bitarray(2 ** 20) # bitarray of length 1048576 (initialized to 0) >>> len(x) 1048576 >>> bitarray('1001 011') # initialize from string (whitespace is ignored) bitarray('1001011') >>> lst = [1, 0, False, True, True] >>> a = bitarray(lst) # initialize from iterable >>> a bitarray('10011') >>> a[2] # indexing a single item will always return an integer 0 >>> a[2:4] # whereas indexing a slice will always return a bitarray bitarray('01') >>> a[2:3] # even when the slice length is just one bitarray('0') >>> a.count(1) 3 >>> a.remove(0) # removes first occurrence of 0 >>> a bitarray('1011') ``` -------------------------------- ### Encode and Decode with bitarray Source: https://pypi.org/project/bitarray Demonstrates how to use the .encode() and .decode() methods of a bitarray object to convert between symbols and their bit representations. ```APIDOC ## Encode and Decode with bitarray ### Description The `.encode()` method takes a dictionary mapping symbols to bitarrays and an iterable, and extends the bitarray object with the encoded symbols found while iterating. The `.decode()` method returns an iterable of the symbols. ### Usage ```python from bitarray import bitarray d = {'H':bitarray('111'), 'e':bitarray('0'), 'l':bitarray('110'), 'o':bitarray('10')} a = bitarray() a.encode(d, 'Hello') print(a) # Output: bitarray('111011011010') print(list(a.decode(d))) # Output: ['H', 'e', 'l', 'l', 'o'] print(''.join(a.decode(d))) # Output: Hello ``` ``` -------------------------------- ### fill() Source: https://pypi.org/project/bitarray Pads the bitarray with zeros until its length is a multiple of 8 and returns the number of bits added. ```APIDOC ## fill() ### Description Add zeros to the end of the bitarray, such that the length will be a multiple of 8, and return the number of bits added [0..7]. ### Method `bitarray.fill()` ### Returns - int: The number of bits added (0 to 7). ``` -------------------------------- ### buffer_info() Source: https://pypi.org/project/bitarray Returns a named tuple containing detailed information about the bitarray's underlying buffer. ```APIDOC ## buffer_info() ### Description Return named tuple with following fields: 0. address: memory address of buffer 1. nbytes: buffer size (in bytes) 2. endian: bit-endianness as a string 3. padbits: number of pad bits 4. alloc: allocated memory for buffer (in bytes) 5. readonly: memory is read-only (bool) 6. imported: buffer is imported (bool) 7. exports: number of buffer exports ### Method `bitarray.buffer_info()` ### Returns - BufferInfo: A named tuple with buffer details. ``` -------------------------------- ### Bitwise Operators on Bitarrays Source: https://pypi.org/project/bitarray Explains and demonstrates the usage of bitwise operators like NOT (~), XOR (^), AND (&=), left shift (<<=), and right shift (>>). ```python >>> a = bitarray('101110001') >>> ~a # invert bitarray('010001110') >>> b = bitarray('111001011') >>> a ^ b # bitwise XOR bitarray('010111010') >>> a &= b # inplace AND >>> a bitarray('101000001') >>> a <<= 2 # in-place left-shift by 2 >>> a bitarray('100000100') >>> b >> 1 # return b right-shifted by 1 bitarray('011100101') ``` -------------------------------- ### Setting Bitarray Ranges with 0 or 1 Source: https://pypi.org/project/bitarray Demonstrates setting all elements within a specified range to 0 or 1, similar to `setall()` but for a slice. ```python >>> a = bitarray(30) >>> a[:] = 0 # set all elements to 0 - equivalent to a.setall(0) >>> a[10:25] = 1 # set elements in range(10, 25) to 1 >>> a bitarray('000000000011111111111111100000') ``` -------------------------------- ### all() Source: https://pypi.org/project/bitarray Checks if all bits in the bitarray are set to 1. This is a faster alternative to the global `all()` function. ```APIDOC ## all() ### Description Return True when all bits in bitarray are 1. a.all() is a faster version of all(a). ### Method Method call on a bitarray object. ### Returns - bool: True if all bits are 1, False otherwise. ``` -------------------------------- ### serialize Source: https://pypi.org/project/bitarray Returns a serialized representation of the bitarray. ```APIDOC ## serialize ### Description Return a serialized representation of the bitarray, which may be passed to deserialize(). It efficiently represents the bitarray object (including its bit-endianness) and is guaranteed not to change in future releases. ### Parameters - **bitarray** (bitarray) - The bitarray to serialize. ### Returns - bytes: A serialized representation of the bitarray. ``` -------------------------------- ### urandom Source: https://pypi.org/project/bitarray Generates a random bitarray using os.urandom(). ```APIDOC ## urandom ### Description Return random bitarray of length n (uses os.urandom()). ### Parameters - **n** (int) - The length of the bitarray. - **endian** (str, optional) - The endianness ('big' or 'little'). ### Returns - bitarray: A random bitarray of length n. ``` -------------------------------- ### bitarray Constructor Source: https://pypi.org/project/bitarray Details the constructor for the `bitarray` object, including initialization options and endianness. ```APIDOC ## The bitarray object ### Constructor `bitarray(initializer=0, /, endian='big', buffer=None) -> bitarray` Returns a new bitarray object. The initializer can be an integer (for length), a string of '0's and '1's, an iterable of 0s or 1s, or bytes/bytearray. ### Parameters - **initializer**: (int, str, iterable, bytes, bytearray) - Optional. The initial value for the bitarray. - **endian**: (str) - Optional. Specifies the bit-endianness ('big' or 'little'). Defaults to 'big'. - **buffer**: (object) - Optional. An object exposing a buffer interface. Cannot be used with initializer. ### Examples ```python # From integer length a = bitarray(10) # From string b = bitarray('101101') # From iterable c = bitarray([1, 0, 1, 0, 1]) # From bytes d = bitarray(b'\x06') # Represents bitarray('00000110') # With endianness e = bitarray('101', endian='little') ``` ``` -------------------------------- ### strip Source: https://pypi.org/project/bitarray Returns a new bitarray with leading/trailing zeros stripped. ```APIDOC ## strip ### Description Return a new bitarray with zeros stripped from left, right or both ends. ### Parameters - **bitarray** (bitarray) - The bitarray to strip. - **mode** (str, optional) - The mode for stripping zeros. Allowed values are 'left', 'right', 'both'. Defaults to 'right'. ### Returns - bitarray: A new bitarray with specified zeros stripped. ``` -------------------------------- ### Decode with a Decodetree Source: https://pypi.org/project/bitarray Shows how to use a `decodetree` object for faster decoding when dealing with large codes and many decode calls. ```APIDOC ## Decode with a Decodetree ### Description For scenarios with large codes and frequent decoding, creating a `decodetree` object can significantly improve performance by pre-compiling the decoding structure. ### Usage ```python from bitarray import bitarray, decodetree t = decodetree({'a': bitarray('0'), 'b': bitarray('1')}) a = bitarray('0110') print(list(a.decode(t))) # Output: ['a', 'b', 'b', 'a'] ``` ``` -------------------------------- ### any() Source: https://pypi.org/project/bitarray Checks if any bit in the bitarray is set to 1. This is a faster alternative to the global `any()` function. ```APIDOC ## any() ### Description Return True when any bit in bitarray is 1. a.any() is a faster version of any(a). ### Method Method call on a bitarray object. ### Returns - bool: True if any bit is 1, False otherwise. ``` -------------------------------- ### fromfile(f, n=-1) Source: https://pypi.org/project/bitarray Extends the bitarray by reading bytes from a file-like object. ```APIDOC ## fromfile(f, n=-1) ### Description Extend bitarray with up to n bytes read from file object f (or any other binary stream what supports a .read() method, e.g. io.BytesIO). Each read byte will add eight bits to the bitarray. When n is omitted or negative, reads and extends all data until EOF. When n is non-negative but exceeds the available data, EOFError is raised. However, the available data is still read and extended. ### Method `bitarray.fromfile(f, n=-1)` ### Parameters #### Path Parameters - **f** (file-like object): The file or stream to read from. - **n** (int): The maximum number of bytes to read. Defaults to -1 (read all data until EOF). ``` -------------------------------- ### test Function Source: https://pypi.org/project/bitarray Runs the self-test for the bitarray module. ```APIDOC ## test(verbosity=1) ### Description Run self-test, and return unittest.runner.TextTestResult object. ### Parameters - **verbosity**: (int, optional) - Controls the verbosity of the test output. Defaults to 1. ``` -------------------------------- ### pprint Source: https://pypi.org/project/bitarray Pretty-prints a bitarray object to a specified stream. ```APIDOC ## pprint ### Description Pretty-print bitarray object to stream, defaults is sys.stdout. By default, bits are grouped in bytes (8 bits), and 64 bits per line. Non-bitarray objects are printed using pprint.pprint(). ### Parameters - **bitarray** (bitarray) - The bitarray object to print. - **stream** (file-like object, optional) - The stream to print to. Defaults to sys.stdout. - **group** (int, optional) - The number of bits to group together. Defaults to 8. - **indent** (int, optional) - The indentation level. Defaults to 4. - **width** (int, optional) - The maximum line width. Defaults to 80. ``` -------------------------------- ### Assigning Booleans to Bitarray Slices Source: https://pypi.org/project/bitarray Shows a more efficient way to set slice elements to a uniform boolean value (True/False) compared to creating and assigning a temporary bitarray. ```python >>> a = 20 * bitarray('0') >>> a[1:15:3] = True >>> a bitarray('01001001001001000000') ``` ```python >>> a = 20 * bitarray('0') >>> a[1:15:3] = 5 * bitarray('1') >>> a bitarray('01001001001001000000') ``` -------------------------------- ### tolist Source: https://pypi.org/project/bitarray Converts the bitarray to a list of integers (0s and 1s). ```APIDOC ## tolist ### Description Return bitarray as list of integers. a.tolist() equals list(a). Note that the list object being created will require 32 or 64 times more memory (depending on the machine architecture) than the bitarray object, which may cause a memory error if the bitarray is very large. ### Returns A list of integers representing the bitarray. ``` -------------------------------- ### ones Source: https://pypi.org/project/bitarray Creates a bitarray of a specified length with all bits set to 1. ```APIDOC ## ones ### Description Create a bitarray of length n, with all values 1, and optional bit-endianness (little or big). ### Parameters - **n** (int) - The desired length of the bitarray. - **endian** (str, optional) - The endianness ('big' or 'little'). ### Returns - bitarray: A bitarray of length n with all bits set to 1. ``` -------------------------------- ### Encode and Decode with Prefix Codes Source: https://pypi.org/project/bitarray Use the .encode() method to convert a string into a bitarray using a provided dictionary of symbols to bitarrays. The .decode() method can then reconstruct the original symbols from the bitarray. ```python >>> d = {'H':bitarray('111'), 'e':bitarray('0'), ... 'l':bitarray('110'), 'o':bitarray('10')} ... ``` ```python >>> a = bitarray() >>> a.encode(d, 'Hello') >>> a bitarray('111011011010') ``` ```python >>> list(a.decode(d)) ['H', 'e', 'l', 'l', 'o'] ``` ```python >>> ''.join(a.decode(d)) 'Hello' ``` -------------------------------- ### to01 Source: https://pypi.org/project/bitarray Converts the bitarray to a string of '0's and '1's, with optional grouping and separator. ```APIDOC ## to01 ### Description Return bitarray as (Unicode) string of 0s and 1s. The bits are grouped into group bits (default is no grouping). When grouped, the string sep is inserted between groups of group characters, default is a space. ### Parameters - **group** (int, optional): The number of bits to group together. Defaults to 0 (no grouping). - **sep** (str, optional): The separator string to insert between groups. Defaults to a space (' '). ### Returns A string representation of the bitarray. ``` -------------------------------- ### copy() Source: https://pypi.org/project/bitarray Returns a shallow copy of the bitarray, preserving its bit-endianness. ```APIDOC ## copy() ### Description Return copy of bitarray (with same bit-endianness). ### Method `bitarray.copy()` ### Returns - bitarray: A new bitarray object that is a copy of the original. ``` -------------------------------- ### setall Source: https://pypi.org/project/bitarray Sets all elements in the bitarray to a specified boolean value. ```APIDOC ## setall ### Description Set all elements in bitarray to value. Note that a.setall(value) is equivalent to a[:] = value. ### Parameters - **value** (bool): The boolean value to set all elements to. ### Returns None ``` -------------------------------- ### unpack Source: https://pypi.org/project/bitarray Converts the bitarray to bytes, using specified byte mappings for zero and one bits. ```APIDOC ## unpack ### Description Return bytes that contain one byte for each bit in the bitarray, using specified mapping. ### Parameters - **zero** (bytes, optional): The byte to represent a 0 bit. Defaults to b'\x00'. - **one** (bytes, optional): The byte to represent a 1 bit. Defaults to b'\x01'. ### Returns A bytes object representing the unpacked bitarray. ``` -------------------------------- ### pack(bytes) Source: https://pypi.org/project/bitarray Extends the bitarray from a bytes-like object, where each byte maps to a single bit. ```APIDOC ## pack(bytes) ### Description Extend bitarray from a bytes-like object, where each byte corresponds to a single bit. The byte b'\x00' maps to bit 0 and all other bytes map to bit 1. This method, as well as the .unpack() method, are meant for efficient transfer of data between bitarray objects to other Python objects (for example NumPy’s ndarray object) which have a different memory view. ### Method `bitarray.pack(bytes)` ### Parameters #### Path Parameters - **bytes** (bytes-like object): The bytes to pack into bits. ``` -------------------------------- ### reverse() Source: https://pypi.org/project/bitarray Reverses the order of all bits in the bitarray in-place. ```APIDOC ## reverse() ### Description Reverse all bits in bitarray (in-place). ### Method `bitarray.reverse()` ``` -------------------------------- ### Frozenbitarray Source: https://pypi.org/project/bitarray Introduces the `frozenbitarray` object, which is an immutable and hashable version of `bitarray`, suitable for use as dictionary keys. ```APIDOC ## Frozenbitarrays ### Description A `frozenbitarray` is an immutable and hashable version of `bitarray`. This immutability allows it to be used as a key in dictionaries or as an element in sets. ### Usage ```python from bitarray import frozenbitarray key = frozenbitarray('1100011') d = {key: 'some value'} print(d) # Attempting to modify a frozenbitarray raises a TypeError try: key[3] = 1 except TypeError as e: print(e) # Output: frozenbitarray is immutable ``` ``` -------------------------------- ### clear() Source: https://pypi.org/project/bitarray Removes all bits from the bitarray, making it empty. ```APIDOC ## clear() ### Description Remove all items from bitarray. ### Method `bitarray.clear()` ``` -------------------------------- ### Decode with a Pre-built Decode Tree Source: https://pypi.org/project/bitarray For frequent decoding operations with large prefix codes, create a decodetree object for improved performance. Pass this tree object to the .decode() method instead of the dictionary. ```python >>> from bitarray import bitarray, decodetree >>> t = decodetree({'a': bitarray('0'), 'b': bitarray('1')}) >>> a = bitarray('0110') >>> list(a.decode(t)) ['a', 'b', 'b', 'a'] ``` -------------------------------- ### frombytes(bytes) Source: https://pypi.org/project/bitarray Extends the bitarray with bits from a bytes-like object. ```APIDOC ## frombytes(bytes) ### Description Extend bitarray with raw bytes from a bytes-like object. Each added byte will add eight bits to the bitarray. ### Method `bitarray.frombytes(bytes)` ### Parameters #### Path Parameters - **bytes** (bytes-like object): The bytes to convert into bits and append. ``` -------------------------------- ### Bitarray Slice Assignment and Deletion Source: https://pypi.org/project/bitarray Illustrates modifying bitarrays using slice assignment with integers or bitarrays, and deleting slices. Also shows concatenation with '+='. ```python >>> a = bitarray(50) >>> a.setall(0) # set all elements in a to 0 >>> a[11:37:3] = 9 * bitarray('1') >>> a bitarray('00000000000100100100100100100100100100000000000000') >>> del a[12::3] >>> a bitarray('0000000000010101010101010101000000000') >>> a[-6:] = bitarray('10011') >>> a bitarray('000000000001010101010101010100010011') >>> a += bitarray('000111') >>> a[9:] bitarray('001010101010101010100010011000111') ``` -------------------------------- ### correspond_all(a, b) Source: https://pypi.org/project/bitarray Calculates counts of bitwise AND and NOT operations between two bitarrays. ```APIDOC ## correspond_all a, b ### Description Return tuple with counts of: ~a & ~b, ~a & b, a & ~b, a & b ### Parameters - **a** (bitarray) - The first bitarray. - **b** (bitarray) - The second bitarray. ### Returns - **tuple** - A tuple containing the counts of the four specified bitwise combinations. ``` -------------------------------- ### huffman_code(dict, endian=None) Source: https://pypi.org/project/bitarray Generates a Huffman code dictionary from a frequency map. ```APIDOC ## huffman_code dict, endian=None ### Description Generates a Huffman code dictionary from a frequency map. This function is part of the Huffman coding utilities. ### Parameters - **dict** (dict) - A dictionary mapping symbols to their frequencies. - **endian** (str, optional) - The endianness ('little' or 'big'). Defaults to None. ### Returns - **dict** - A dictionary mapping symbols to their Huffman codes (as bitarrays). ``` -------------------------------- ### tofile Source: https://pypi.org/project/bitarray Writes the bitarray buffer to a file object. ```APIDOC ## tofile ### Description Write bitarray buffer to file object f. ### Parameters - **f** (file object): The file object to write to. ### Returns None ``` -------------------------------- ### decodetree Function Source: https://pypi.org/project/bitarray Creates a binary tree object for decoding from a prefix code. ```APIDOC ## decodetree(code, /) ### Description Given a prefix code (a dict mapping symbols to bitarrays), create a binary tree object to be passed to .decode(). New in version 1.6 ### Parameters - **code**: (dict) - A dictionary mapping symbols to bitarrays representing the prefix code. ``` -------------------------------- ### ba2base(n, bitarray, group=0, sep=' ') Source: https://pypi.org/project/bitarray Converts a bitarray to its string representation in a specified base. ```APIDOC ## ba2base n, bitarray, group=0, sep=' ' ### Description Return a string containing the base n ASCII representation of the bitarray. Allowed values for n are 2, 4, 8, 16, 32 and 64. The bitarray has to be multiple of length 1, 2, 3, 4, 5 or 6 respectively. For n=32 the RFC 4648 Base32 alphabet is used, and for n=64 the standard base 64 alphabet is used. When grouped, the string sep is inserted between groups of group characters, default is a space. ### Parameters - **n** (int) - The base for the representation (2, 4, 8, 16, 32, 64). - **bitarray** (bitarray) - The bitarray to convert. - **group** (int, optional) - The number of characters per group for separated output. Defaults to 0 (no grouping). - **sep** (str, optional) - The separator string to insert between groups. Defaults to a space. ### Returns - **str** - The string representation of the bitarray in the specified base. ``` -------------------------------- ### byteswap(a, n=) Source: https://pypi.org/project/bitarray Reverses every n consecutive bytes of a buffer in-place. ```APIDOC ## byteswap a, n= ### Description Reverse every n consecutive bytes of a in-place. By default, all bytes are reversed. Note that n is not limited to 2, 4 or 8, but can be any positive integer. Also, a may be any object that exposes a writable buffer. Nothing about this function is specific to bitarray objects. ### Parameters - **a** (buffer) - The buffer object to modify. - **n** (int, optional) - The number of bytes to reverse. Defaults to reversing all bytes. ### Returns None. The operation is performed in-place. ``` -------------------------------- ### zeros(n, endian=None) Source: https://pypi.org/project/bitarray Creates a new bitarray of a specified length, initialized with all zero values. Optionally, the bit-endianness can be set. ```APIDOC ## zeros(n, endian=None) ### Description Create a bitarray of length n, with all values 0, and optional bit-endianness (little or big). ### Parameters #### Path Parameters - **n** (int) - Required - The desired length of the bitarray. - **endian** (str, optional) - The bit-endianness ('little' or 'big'). Defaults to None. ### Returns - **bitarray** - A new bitarray of length n with all bits set to 0. ``` -------------------------------- ### insert(index, value) Source: https://pypi.org/project/bitarray Inserts a bit value at a specific index in the bitarray. ```APIDOC ## insert(index, value) ### Description Insert value into bitarray before index. ### Method `bitarray.insert(index, value)` ### Parameters #### Path Parameters - **index** (int): The index before which to insert the value. - **value** (int): The bit value (0 or 1) to insert. ``` -------------------------------- ### count(value=1, start=0, stop=end, step=1) Source: https://pypi.org/project/bitarray Counts the occurrences of a specific bit value or sub-bitarray within a specified range and step. ```APIDOC ## count(value=1, start=0, stop=end, step=1) ### Description Number of occurrences of value bitarray within [start:stop:step]. Optional arguments start, stop and step are interpreted in slice notation, meaning a.count(value, start, stop, step) equals a[start:stop:step].count(value). The value may also be a sub-bitarray. In this case non-overlapping occurrences are counted within [start:stop] (step must be 1). ### Method `bitarray.count(value=1, start=0, stop=end, step=1)` ### Parameters #### Path Parameters - **value** (int or bitarray): The bit value (0 or 1) or sub-bitarray to count. Defaults to 1. - **start** (int): The starting index (inclusive). Defaults to 0. - **stop** (int): The ending index (exclusive). Defaults to the end of the bitarray. - **step** (int): The step size for slicing. Defaults to 1. ``` -------------------------------- ### index(sub_bitarray, start=0, stop=end, right=False) Source: https://pypi.org/project/bitarray Finds the index of the first or last occurrence of a sub-bitarray within a specified range, raising ValueError if not found. ```APIDOC ## index(sub_bitarray, start=0, stop=end, right=False) ### Description Return lowest (or rightmost when right=True) index where sub_bitarray is found, such that sub_bitarray is contained within [start:stop]. Raises ValueError when sub_bitarray is not present. ### Method `bitarray.index(sub_bitarray, start=0, stop=end, right=False)` ### Parameters #### Path Parameters - **sub_bitarray** (bitarray): The sub-bitarray to search for. - **start** (int): The starting index (inclusive). Defaults to 0. - **stop** (int): The ending index (exclusive). Defaults to the end of the bitarray. - **right** (bool): If True, search from the right (last occurrence). Defaults to False. ### Returns - int: The index of the sub-bitarray. ### Raises - ValueError: If the sub_bitarray is not found. ``` -------------------------------- ### any_and(a, b) Source: https://pypi.org/project/bitarray Efficiently checks if there is any common set bit between two bitarrays. ```APIDOC ## any_and a, b ### Description Efficient implementation of any(a & b). ### Parameters - **a** (bitarray) - The first bitarray. - **b** (bitarray) - The second bitarray. ### Returns - **bool** - True if there is at least one common set bit, False otherwise. ``` -------------------------------- ### base2ba(n, asciistr, endian=None) Source: https://pypi.org/project/bitarray Converts a string representation in a specified base to a bitarray. ```APIDOC ## base2ba n, asciistr, endian=None ### Description Bitarray of base n ASCII representation. Allowed values for n are 2, 4, 8, 16, 32 and 64. For n=32 the RFC 4648 Base32 alphabet is used, and for n=64 the standard base 64 alphabet is used. Whitespace is ignored. ### Parameters - **n** (int) - The base of the ASCII string (2, 4, 8, 16, 32, 64). - **asciistr** (str) - The ASCII string to convert. - **endian** (str, optional) - The endianness ('little' or 'big'). Defaults to None. ### Returns - **bitarray** - The resulting bitarray. ``` -------------------------------- ### pop(index=-1) Source: https://pypi.org/project/bitarray Removes and returns the bit at the specified index (default is the last bit). ```APIDOC ## pop(index=-1) ### Description Remove and return item at index (default last). Raises IndexError if index is out of range. ### Method `bitarray.pop(index=-1)` ### Parameters #### Path Parameters - **index** (int): The index of the bit to remove. Defaults to -1 (the last bit). ### Returns - int: The removed bit (0 or 1). ### Raises - IndexError: If the index is out of range. ``` -------------------------------- ### canonical_huffman(dict) Source: https://pypi.org/project/bitarray Calculates the canonical Huffman code from a frequency map. ```APIDOC ## canonical_huffman dict ### Description Given a frequency map, a dictionary mapping symbols to their frequency, calculate the canonical Huffman code. Returns a tuple containing: 0. the canonical Huffman code as a dict mapping symbols to bitarrays 1. a list containing the number of symbols of each code length 2. a list of symbols in canonical order Note: the two lists may be used as input for canonical_decode(). ### Parameters - **dict** (dict) - A dictionary mapping symbols to their frequencies. ### Returns - **tuple** - A tuple containing the Huffman code dictionary, code length list, and symbol list. ``` -------------------------------- ### Create and Use Frozenbitarrays Source: https://pypi.org/project/bitarray Frozenbitarrays are immutable and hashable, allowing them to be used as dictionary keys. Attempting to modify a frozenbitarray will raise a TypeError. ```python >>> from bitarray import frozenbitarray >>> key = frozenbitarray('1100011') >>> {key: 'some value'} {frozenbitarray('1100011'): 'some value'} ``` ```python >>> key[3] = 1 Traceback (most recent call last): ... TypeError: frozenbitarray is immutable ``` -------------------------------- ### bitarray Data Descriptors Source: https://pypi.org/project/bitarray These are data descriptors available for bitarray objects, providing information about their properties. ```APIDOC ## bitarray Data Descriptors ### endian - **Type**: str - **Description**: bit-endianness as Unicode string. New in version 3.4: replaces former .endian() method. ### nbytes - **Type**: int - **Description**: buffer size in bytes. ### padbits - **Type**: int - **Description**: number of pad bits. ### readonly - **Type**: bool - **Description**: bool indicating whether buffer is read-only. ``` -------------------------------- ### count_and(a, b) Source: https://pypi.org/project/bitarray Efficiently counts the number of set bits in the bitwise AND of two bitarrays. ```APIDOC ## count_and a, b ### Description Return (a & b).count() in a memory efficient manner, as no intermediate bitarray object gets created. ### Parameters - **a** (bitarray) - The first bitarray. - **b** (bitarray) - The second bitarray. ### Returns - **int** - The count of set bits in the result of (a & b). ``` -------------------------------- ### random_k Source: https://pypi.org/project/bitarray Generates a pseudo-random bitarray of a given length with a specific number of set bits. ```APIDOC ## random_k ### Description Return (pseudo-) random bitarray of length n with k elements set to one. Mathematically equivalent to setting (in a bitarray of length n) all bits at indices random.sample(range(n), k) to one. The random bitarrays are reproducible when giving Python’s random.seed() a specific seed value. ### Parameters - **n** (int) - The length of the bitarray. - **k** (int) - The number of bits to set to one. - **endian** (str, optional) - The endianness ('big' or 'little'). ### Returns - bitarray: A pseudo-random bitarray of length n with k bits set to one. ``` -------------------------------- ### sc_encode Source: https://pypi.org/project/bitarray Compresses a sparse bitarray into a binary representation. ```APIDOC ## sc_encode ### Description Compress a sparse bitarray and return its binary representation. This representation is useful for efficiently storing sparse bitarrays. Use sc_decode() for decompressing (decoding). ### Parameters - **bitarray** (bitarray) - The sparse bitarray to compress. ### Returns - bytes: The binary representation of the compressed bitarray. ``` -------------------------------- ### parity Source: https://pypi.org/project/bitarray Calculates the parity of a bitarray. ```APIDOC ## parity ### Description Return parity of bitarray a. parity(a) is equivalent to a.count() % 2 but more efficient. ### Parameters - **a** (bitarray) - The bitarray to calculate parity for. ### Returns - int: The parity of the bitarray (0 or 1). ``` -------------------------------- ### find(sub_bitarray, start=0, stop=end, right=False) Source: https://pypi.org/project/bitarray Finds the first or last occurrence of a sub-bitarray within a specified range. ```APIDOC ## find(sub_bitarray, start=0, stop=end, right=False) ### Description Return lowest (or rightmost when right=True) index where sub_bitarray is found, such that sub_bitarray is contained within [start:stop]. Return -1 when sub_bitarray is not found. ### Method `bitarray.find(sub_bitarray, start=0, stop=end, right=False)` ### Parameters #### Path Parameters - **sub_bitarray** (bitarray): The sub-bitarray to search for. - **start** (int): The starting index (inclusive). Defaults to 0. - **stop** (int): The ending index (exclusive). Defaults to the end of the bitarray. - **right** (bool): If True, search from the right (last occurrence). Defaults to False. ``` -------------------------------- ### sort Source: https://pypi.org/project/bitarray Sorts all bits in the bitarray in-place. Can sort in ascending or descending order. ```APIDOC ## sort ### Description Sort all bits in bitarray (in-place). ### Parameters - **reverse** (bool, optional): If True, sort in descending order. Defaults to False. ### Returns None ``` -------------------------------- ### random_p Source: https://pypi.org/project/bitarray Generates a pseudo-random bitarray where each bit has a given probability of being one. ```APIDOC ## random_p ### Description Return (pseudo-) random bitarray of length n, where each bit has probability p of being one (independent of any other bits). Mathematically equivalent to bitarray((random() < p for _ in range(n)), endian), but much faster for large n. The random bitarrays are reproducible when giving Python’s random.seed() with a specific seed value. This function requires Python 3.12 or higher, as it depends on the standard library function random.binomialvariate(). Raises NotImplementedError when Python version is too low. ### Parameters - **n** (int) - The length of the bitarray. - **p** (float, optional) - The probability of a bit being one. Defaults to 0.5. - **endian** (str, optional) - The endianness ('big' or 'little'). ### Returns - bitarray: A pseudo-random bitarray of length n with each bit having probability p of being one. ``` -------------------------------- ### search Source: https://pypi.org/project/bitarray Returns an iterator over indices where a sub-bitarray is found within a specified range. Supports searching in ascending or descending order. ```APIDOC ## search ### Description Return iterator over indices where sub_bitarray is found, such that sub_bitarray is contained within [start:stop]. The indices are iterated in ascending order (from lowest to highest), unless right=True, which will iterate in descending order (starting with rightmost match). ### Parameters - **sub_bitarray**: The bitarray to search for. - **start** (int, optional): The starting index of the slice to search within. Defaults to 0. - **stop** (int, optional): The ending index of the slice to search within. Defaults to the end of the bitarray. - **right** (bool, optional): If True, iterate in descending order. Defaults to False. ### Returns An iterator over the indices where the sub_bitarray is found. ``` -------------------------------- ### bytereverse(start=0, stop=end) Source: https://pypi.org/project/bitarray Reverses the bits within each byte in a specified range of the bitarray in-place. ```APIDOC ## bytereverse(start=0, stop=end) ### Description For each byte in byte-range(start, stop) reverse bits in-place. The start and stop indices are given in terms of bytes (not bits). Also note that this method only changes the buffer; it does not change the bit-endianness of the bitarray object. Pad bits are left unchanged such that two consecutive calls will always leave the bitarray unchanged. ### Method `bitarray.bytereverse(start=0, stop=end)` ### Parameters #### Path Parameters - **start** (int): The starting byte index (inclusive). Defaults to 0. - **stop** (int): The ending byte index (exclusive). Defaults to the end of the buffer. ``` -------------------------------- ### int2ba Source: https://pypi.org/project/bitarray Converts an integer to a bitarray with optional length, endianness, and signed representation. ```APIDOC ## int2ba ### Description Convert the given integer to a bitarray (with given bit-endianness, and no leading (big-endian) / trailing (little-endian) zeros), unless the length of the bitarray is provided. An OverflowError is raised if the integer is not representable with the given number of bits. signed determines whether two’s complement is used to represent the integer, and requires length to be provided. ### Parameters - **int** (integer) - The integer to convert. - **length** (int, optional) - The desired length of the bitarray. - **endian** (str, optional) - The endianness ('big' or 'little'). - **signed** (bool, optional) - Whether to use two’s complement representation. ``` -------------------------------- ### intervals Source: https://pypi.org/project/bitarray Computes uninterrupted intervals of 1s and 0s in a bitarray. ```APIDOC ## intervals ### Description Compute all uninterrupted intervals of 1s and 0s, and return an iterator over tuples (value, start, stop). The intervals are guaranteed to be in order, and their size is always non-zero (stop - start > 0). ### Parameters - **bitarray** (bitarray) - The bitarray to analyze. ### Returns - iterator: An iterator yielding tuples of (value, start, stop) for each interval. ``` -------------------------------- ### deserialize(bytes) Source: https://pypi.org/project/bitarray Reconstructs a bitarray from its byte representation. ```APIDOC ## deserialize bytes ### Description Return a bitarray given a bytes-like representation such as returned by serialize(). ### Parameters - **bytes** (bytes-like) - The byte representation of the bitarray. ### Returns - **bitarray** - The reconstructed bitarray. ``` -------------------------------- ### decode(code) Source: https://pypi.org/project/bitarray Decodes the bitarray using a provided prefix code, returning an iterator over the decoded symbols. ```APIDOC ## decode(code) ### Description Given a prefix code (a dict mapping symbols to bitarrays, or decodetree object), decode content of bitarray and return an iterator over corresponding symbols. ### Method `bitarray.decode(code)` ### Parameters #### Path Parameters - **code** (dict or decodetree object): The prefix code used for decoding. ``` -------------------------------- ### ba2hex(bitarray, group=0, sep=' ') Source: https://pypi.org/project/bitarray Converts a bitarray to its hexadecimal string representation. ```APIDOC ## ba2hex bitarray, group=0, sep=' ' ### Description Return a string containing the hexadecimal representation of the bitarray (which has to be multiple of 4 in length). When grouped, the string sep is inserted between groups of group characters, default is a space. ### Parameters - **bitarray** (bitarray) - The bitarray to convert. - **group** (int, optional) - The number of characters per group for separated output. Defaults to 0 (no grouping). - **sep** (str, optional) - The separator string to insert between groups. Defaults to a space. ### Returns - **hexstr** - The hexadecimal string representation of the bitarray. ``` -------------------------------- ### append(item) Source: https://pypi.org/project/bitarray Appends a single bit item to the end of the bitarray. ```APIDOC ## append(item) ### Description Append item to the end of the bitarray. ### Method `bitarray.append(item)` ### Parameters #### Path Parameters - **item** (int): The bit to append (0 or 1). ``` -------------------------------- ### canonical_decode(bitarray, count, symbol) Source: https://pypi.org/project/bitarray Decodes a bitarray using canonical Huffman decoding tables. ```APIDOC ## canonical_decode bitarray, count, symbol ### Description Decode bitarray using canonical Huffman decoding tables where count is a sequence containing the number of symbols of each length and symbol is a sequence of symbols in canonical order. ### Parameters - **bitarray** (bitarray) - The bitarray to decode. - **count** (sequence) - A sequence containing the number of symbols of each length. - **symbol** (sequence) - A sequence of symbols in canonical order. ### Returns - **iterator** - An iterator yielding the decoded symbols. ``` -------------------------------- ### vl_encode Source: https://pypi.org/project/bitarray Encodes a bitarray into a variable length binary representation. ```APIDOC ## vl_encode ### Description Return variable length binary representation of bitarray. This representation is useful for efficiently storing small bitarray in a binary stream. Use vl_decode() for decoding. ### Parameters - **bitarray** (bitarray) - The bitarray to encode. ### Returns - bytes: The variable length binary representation of the bitarray. ``` -------------------------------- ### vl_decode Source: https://pypi.org/project/bitarray Decodes a variable length binary stream into a bitarray. ```APIDOC ## vl_decode ### Description Decode binary stream (an integer iterator, or bytes-like object), and return the decoded bitarray. This function consumes only one bitarray and leaves the remaining stream untouched. Use vl_encode() for encoding. ### Parameters - **stream** (iterator or bytes-like object) - The variable length binary stream to decode. - **endian** (str, optional) - The endianness ('big' or 'little'). ### Returns - bitarray: The decoded bitarray. ``` -------------------------------- ### gen_primes(n, endian=None, odd=False) Source: https://pypi.org/project/bitarray Generates a bitarray where active indices correspond to prime numbers. ```APIDOC ## gen_primes n, endian=None, odd=False ### Description Generate a bitarray of length n in which active indices are prime numbers. By default (odd=False), active indices correspond to prime numbers directly. When odd=True, only odd prime numbers are represented in the resulting bitarray a, and a[i] corresponds to 2*i+1 being prime or not. Apart from working with prime numbers, this function is useful for testing, as it provides a simple way to create a well-defined bitarray of any length. ### Parameters - **n** (int) - The desired length of the bitarray. - **endian** (str, optional) - The endianness ('little' or 'big'). Defaults to None. - **odd** (bool, optional) - If True, only consider odd prime numbers. Defaults to False. ### Returns - **bitarray** - A bitarray where active indices represent prime numbers. ``` -------------------------------- ### tobytes Source: https://pypi.org/project/bitarray Converts the bitarray to a bytes object, padding with zeros if necessary. ```APIDOC ## tobytes ### Description Return the bitarray buffer (pad bits are set to zero). a.tobytes() is equivalent to bytes(a). ### Returns A bytes object representing the bitarray. ```