ice-wind
ice-wind

Reputation: 868

Change specific bits in a value

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)

Upvotes: 1

Views: 1078

Answers (1)

You can do something like this:

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

Demonstration:

>>> set_bits(341, 2, 6, 6, 9)
309

Upvotes: 1

Related Questions