I have an integer with a value 7 (0b00000111) And I would like to replace it with a function to 13 (0b00001101). What is
You just need:
def set_bit(v, index, x):
"""Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value."""
mask = 1 << index # Compute mask, an integer with just bit 'index' set.
v &= ~mask # Clear the bit indicated by the mask (if x is False)
if x:
v |= mask # If x was True, set the bit indicated by the mask.
return v # Return the result, we're done.
>>> set_bit(7, 3, 1)
15
>>> set_bit(set_bit(7, 1, 0), 3, 1)
13
Note that bit numbers (index) are from 0, with 0 being the least significant bit.
Also note that the new value is returned, there's no way to modify an integer "in place" like you show (at least I don't think so).