如何解决更改值中的特定位
我已经有一个能够从值中提取特定位的函数:
def get_bits(n,start,end,length=64):
"""Read bits [<start>:<end>] of <n> and return them
<length> is the bitlength of <n>"""
shift = length - end
mask = 1 << (end - start) - 1
return (n & (mask << shift)) >> shift
我需要一个类似的函数来改变这些位:
def set_bits(n,newValue,length=64):
"""Set bits [<start>:<end>] of <n> to <newValue> and return it
<length> is the bitlength of <n>"""
pass #How do I do this ?
我试过在纸上弄清楚并查找它,但我担心我的按位数学能力很差,我找不到合适的解决方案
通缉行为示例:
n = 341 #341 is 101010101
newValue = 6 #6 is 0110
n = set_bits(
n = n,start = 2,end = 6,newValue = newValue,length = 9)
# n should now be 309 (100110101)
解决方法
你可以这样做:
def set_bits(n,start,end,new_value,length=64):
# Remove all the bits in the range from the original number
# Do this by using `AND` with the inverse of the bits
n = n & ~((2 ** (end-start) - 1) << (length - end))
# OR with the new value
n = n | new_value << (length - end)
return n
演示:
>>> set_bits(341,2,6,9)
309
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。