Reader¶
- class Reader(bits: Bits | BitArray, pos: int = 0)¶
Wraps a
BitsorBitArrayobject with a bit position for sequential reading.The wrapped bitstring is exposed directly as
bits. If it is aBitArraythen it can be mutated through the reader, for exampler.bits.append('0xff'). Mutating the wrapped object never updatesposautomatically.
Reading and peeking¶
The read and read_list methods interpret bits starting at
pos and advance the position. The matching peek and
peek_list methods return the same values without changing the position.
For example:
>>> r = Reader(Bits('0x160120f'))
>>> r.read(12).hex
'160'
>>> r.pos = 0
>>> r.read('u12')
352
>>> r.read_list('u12, bin3')
[288, '111']
If a read fails then pos is restored to its value before the read.
The position is deliberately lax: assigning to pos, bitpos or
bytepos stores the integer value without checking it against the wrapped
bitstring length. Reading methods will raise an error if the position is not
usable when they need it.
Methods¶
- Reader.read(fmt: str | int | Dtype) int | float | str | Bits | bool | bytes | None¶
Reads from
posaccording to fmt and advances the position.If fmt is an integer then that many bits are returned as a bitstring. If it is a string or
Dtypethen the corresponding dtype is read.
- Reader.read_list(fmt: str | list[str | int | Dtype], **kwargs) list[int | float | str | Bits | bool | bytes | None]¶
Reads one or more format tokens and returns a list of values.
- Reader.peek_list(fmt: str | list[str | int | Dtype], **kwargs) list[int | float | str | Bits | bool | bytes | None]¶
- Reader.read_to(bs: BitsType, *, bytealigned: bool | None = None) Bits¶
Reads up to and including the next occurrence of bs.
- Reader.byte_align() int¶
Aligns
posto the next byte boundary and returns the number of bits skipped.
Properties¶
- Reader.bits: Bits | BitArray¶
The wrapped bitstring object. This is the original object, not a copy.
- Reader.pos: int¶
- Reader.bitpos: int¶
The current bit position. These aliases store any integer value.
- Reader.bytepos: int¶
The current byte position. Reading this property requires
posto be byte aligned and raisesByteAlignErrorotherwise.