70 lines
2.1 KiB
Python
70 lines
2.1 KiB
Python
|
|
def clr_bits(value: int, mask: int) -> int:
|
||
|
|
"""
|
||
|
|
Clear bits specified by mask in the given value.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value (int): The original integer value.
|
||
|
|
mask (int): The mask specifying which bits to clear.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
int: The modified integer value with specified bits cleared.
|
||
|
|
"""
|
||
|
|
return value & ~mask
|
||
|
|
|
||
|
|
def get_bits(value: int, mask: int) -> int:
|
||
|
|
"""
|
||
|
|
Get bits specified by mask from the given value.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value (int): The original integer value.
|
||
|
|
mask (int): The mask specifying which bits to get.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
int: The extracted bits shifted to the right by the offset.
|
||
|
|
"""
|
||
|
|
return value & mask
|
||
|
|
|
||
|
|
def get_bitfield(value: int, mask: int, pos: int) -> int:
|
||
|
|
"""
|
||
|
|
Extract a bitfield from the given value.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value (int): The original integer value.
|
||
|
|
mask (int): The mask specifying the bitfield.
|
||
|
|
pos (int): The position to shift the masked bits.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
int: The extracted bitfield shifted to the right by the position.
|
||
|
|
"""
|
||
|
|
return get_bits(value, mask) >> pos
|
||
|
|
|
||
|
|
def update_bits(value: int, mask: int, new_bits: int) -> int:
|
||
|
|
"""
|
||
|
|
Update bits specified by mask in the given value with new bits.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value (int): The original integer value.
|
||
|
|
mask (int): The mask specifying which bits to update.
|
||
|
|
new_bits (int): The new bits to set in the specified positions.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
int: The modified integer value with specified bits updated.
|
||
|
|
"""
|
||
|
|
|
||
|
|
return clr_bits(value, mask) | get_bits(new_bits, mask)
|
||
|
|
|
||
|
|
def set_bitfield(value: int, mask: int, pos: int, new_bits: int) -> int:
|
||
|
|
"""
|
||
|
|
Set a bitfield in the given value with new bits.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
value (int): The original integer value.
|
||
|
|
mask (int): The mask specifying the bitfield.
|
||
|
|
pos (int): The position to shift the new bits.
|
||
|
|
new_bits (int): The new bits to set in the specified bitfield.
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
int: The modified integer value with specified bitfield updated.
|
||
|
|
"""
|
||
|
|
return update_bits(value, mask, new_bits << pos)
|