Reader

class Reader(bits: Bits | BitArray, pos: int = 0)

Wraps a Bits or BitArray object with a bit position for sequential reading.

The wrapped bitstring is exposed directly as bits. If it is a BitArray then it can be mutated through the reader, for example r.bits.append('0xff'). Mutating the wrapped object never updates pos automatically.

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 pos according 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 Dtype then 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(fmt: str | int | Dtype) int | float | str | Bits | bool | bytes | None

Like read, but leaves pos unchanged.

Reader.peek_list(fmt: str | list[str | int | Dtype], **kwargs) list[int | float | str | Bits | bool | bytes | None]

Like read_list, but leaves pos unchanged.

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 pos to the next byte boundary and returns the number of bits skipped.

Reader.find(bs: BitsType, *, start: int | None = None, end: int | None = None, bytealigned: bool | None = None) int | None

Searches the wrapped bitstring and sets pos to the match position if bs is found. Returns the match position, or None if not found.

Reader.rfind(bs: BitsType, *, start: int | None = None, end: int | None = None, bytealigned: bool | None = None) int | None

Searches backwards and sets pos to the match position if bs is found. Returns the match position, or None if not found.

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 pos to be byte aligned and raises ByteAlignError otherwise.