cbitstruct - Fast C Bitstruct
cbitstruct is a Python library providing a faster C implementation of `bitstruct`. It offers API compatibility with `bitstruct`, allowing for efficient packing and unpacking of bitfields from and to Python data types. The current version is 1.2.0, and releases primarily focus on Python version support and bug fixes, with a focus on stability and performance.
Common errors
-
Segmentation fault (core dumped)
cause `cbitstruct` received invalid input data or a malformed format string, leading to memory access violations in the underlying C code.fixCarefully review the format string and ensure the input values (for `pack`) or binary data (for `unpack`) strictly adhere to the expected format. Common mistakes include providing too few/many arguments for `pack` or providing data shorter than the format string demands for `unpack`. Update to the latest `cbitstruct` version as many such issues have been patched. -
ModuleNotFoundError: No module named 'cbitstruct'
cause The `cbitstruct` package is not installed in the active Python environment or is not accessible on the Python path.fixEnsure `cbitstruct` is installed using `pip install cbitstruct`. If you are using a virtual environment, activate it before installing. Verify the installation by running `python -c "import cbitstruct"`. -
TypeError: 'str' object cannot be interpreted as an integer
cause Attempting to pass a string where an integer (representing a bitfield value) is expected, likely when calling `pack`.fixEnsure all individual values passed to `pack` (after the format string) are integers, even if they represent binary data. For example, `pack('u8', 0b10101010)` or `pack('u8', 170)`, not `pack('u8', '0b10101010')`.
Warnings
- gotcha Incorrect usage of format strings or input values can lead to segmentation faults due to `cbitstruct` being a C extension. This was particularly prevalent in early versions (1.0.0 - 1.0.3).
- gotcha While `cbitstruct` aims for full API compatibility with `bitstruct`, subtle differences in edge cases or error handling might exist. Always test thoroughly when replacing `bitstruct` with `cbitstruct` in critical paths.
Install
-
pip install cbitstruct
Imports
- pack
from cbitstruct import pack
- unpack
from cbitstruct import unpack
- byteswap
from cbitstruct import byteswap
Quickstart
from cbitstruct import pack, unpack
# Pack 8 single-bit unsigned integers into a byte
data = pack('u1u1u1u1u1u1u1u1', 1, 0, 1, 0, 1, 0, 1, 0)
print(f"Packed data: {data!r}") # Expected: b'\xaa'
# Unpack the data back into a tuple of integers
unpacked_data = unpack('u1u1u1u1u1u1u1u1', data)
print(f"Unpacked data: {unpacked_data}") # Expected: (1, 0, 1, 0, 1, 0, 1, 0)
# Example with different format string
value = pack('u4u4', 0xA, 0x5)
print(f"Packed nibbles: {value!r}") # Expected: b'\xa5'