更改值中的特定位
Change specific bits in a value
我已经有一个函数可以从值中提取特定位:
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, start, end, 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, 6, 9)
309
我已经有一个函数可以从值中提取特定位:
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, start, end, 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, 6, 9)
309