hbutils.binary.bool
This module provides boolean type handling for binary I/O operations in C-style format.
The module implements a CBoolType class that allows reading and writing boolean values to binary streams using C language conventions. It provides a pre-configured c_bool instance that matches the size of C’s bool type on the current platform.
CBoolType
- class hbutils.binary.bool.CBoolType(size: int)[source]
Boolean type for binary I/O operations.
This class provides methods to read and write boolean values in binary format, compatible with C language boolean representation.
- __init__(size: int)[source]
Constructor of
CBoolType.- Parameters:
size (int) – Size of boolean type in bytes.
- read(file: BinaryIO) bool[source]
Read boolean value from binary file.
- Parameters:
file (BinaryIO) – Binary file object to read from,
io.BytesIOis supported as well.- Returns:
Boolean value read from the file. Returns True if any byte is non-zero.
- Return type:
bool
- Example::
>>> import io >>> from hbutils.binary import c_bool >>> with io.BytesIO(b'\x01\x00') as file: ... print(c_bool.read(file)) ... print(c_bool.read(file)) True False
- property size: int
Size of the given type in bytes.
- Returns:
The size of the type.
- Return type:
int
- write(file: BinaryIO, val: bool)[source]
Write boolean value to binary IO object.
The boolean value is written as a sequence of bytes with the size specified during initialization. The value is represented as 0x01 for True and 0x00 for False, padded with leading zeros to match the required size.
- Parameters:
file (BinaryIO) – Binary file object to write to,
io.BytesIOis supported as well.val (bool) – Boolean value to write.
- Example::
>>> import io >>> from hbutils.binary import c_bool >>> with io.BytesIO() as file: ... c_bool.write(file, True) ... c_bool.write(file, False) ... print(file.getvalue()) b'\x01\x00'
c_bool
- hbutils.binary.bool.c_bool = <hbutils.binary.bool.CBoolType object>
Pre-configured boolean type instance for reading and writing bool values in C language format.
This instance is configured with the size of C’s bool type on the current platform, ensuring compatibility with C binary data structures.
- Type:
- Examples::
>>> import io >>> from hbutils.binary import c_bool >>> >>> # Reading boolean values >>> with io.BytesIO(b'\x01\x00\x01\x00') as file: ... print(c_bool.read(file)) ... print(c_bool.read(file)) ... print(c_bool.read(file)) ... print(c_bool.read(file)) True False True False
>>> # Writing boolean values >>> with io.BytesIO() as file: ... c_bool.write(file, True) ... c_bool.write(file, False) ... c_bool.write(file, True) ... c_bool.write(file, False) ... print(file.getvalue()) ... b'\x01\x00\x01\x00'