if users need to change the 7th bit in data(data=2, one byte) to be 1, and return the new data, they can use the set_bit_val command as below.
If users need read the 7th bit in data(data=130, one byte), they can use the get_bit_val command as below
def get_bit_val(byte, index):
"""
read the specified bit value
:param byte: the target byte
:param index: the bit index vary from 0 to 7, from right to left
:returns: return the bit value, 0 or 1
"""
if byte & (1 << index):
return 1
else:
return 0
def set_bit_val(byte, index, val):
"""
write the specified it value
:param byte: The target byte
:param index: the bit index vary from 0 to 7, from right to left
:param val: the bit value users want to change
:returns: the byte value after modification
"""
if val:
return byte | (1 << index)
else:
return byte & ~(1 << index)
data =2
print(set_bit_val(data,7,1))
# original data=2, namely 00000010
# data=130,namely set bit 7 as 1,or data=10000010
print(get_bit_val(data,7))
# result is 1,read the 7th bit in data =10000010