BitFields¶
A generic bitfield is a single byte primitive used for extracting bit values from a byte.
Bit values can be retrieved or set using the get_bit(idx) and set_bit(idx, val) methods respectively.
bf = BitField()
bf.set_bit(0, 1)
bf.set_bit(1, True)
bf.get_bit(0)
The BitField class also support getting/setting bits by indexing on an instance.
bf = BitField()
bf[2] = 1
bf[3] = True
Data can be accessed directly via the .data attribute.
bf = BitField()
bf.data = b"\xFF"
Custom BitFields¶
A custom BitField enables several unique features not available with a generic BitField.
The
BitFieldclass internally supports multiple bytes. The length of aBitFieldclass can be adjusted by specifying abyte_lengthclass attribute.Individual bits can be named through the use of the
BitPostyped class attributes. Adding these attributes provides an additional method for accessing bit values.
from byteclasses.primitives import BitField, BitPos
class MyBitField(ByteField):
"""A two byte bit field with two named bit."""
byte_length = 2
first = BitPos(0)
middle = BitPos(8, bit_width = 4)
last = BitPos(15)
bv = MyBitField()
bv.first = 1
bv.middle = 0b1010
bv.last = True