I already have a function able to extract specific bits from 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
I need a similar function to change said bits :
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 ?
I've tried figuring it out on paper and looking it up, but I'm afraid my abilities in bitwise maths are pretty poor and I can't find a solution that fits
Example of wanted behavior :
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)