So, I have an integer with a value 7. (0b00000111) And I would like to replace it with a function to 13. (0b00001101) So what is the best algorithm to replace bytes in an integer? For example:
set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?
解决方案
You just need:
def set_bit(v, index, x):
"""Set the index:th bit of v to x, and return the new value."""
mask = 1 << index
v &= ~mask
if x:
v |= mask
return v
>>> 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.