【CSEN005】Read & Write one bit in a byte value

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
点击显示全文
赞同0
发表评论
分享

手机扫码分享
0
249
收藏
举报
收起
登录
  • 密码登录
  • 验证码登录
还没有账号,立即注册
还没有账号,立即注册
注册
已有账号,立即登录
选择发帖板块
上传文件
举报
请选择举报理由
举报
举报说明