Wystarczy:
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
Należy zauważyć, że nieco liczb (index
) wynosi od 0, z 0 jest najmniej znaczący bit.
Zauważ również, że nowa wartość to zwróciła, nie ma możliwości zmodyfikowania liczby całkowitej "na miejscu", tak jak pokazujesz (przynajmniej nie sądzę).
Podobnie jak w C. http://wiki.python.org/moin/BitwiseOperators – Kos
Uważaj na swoje prefiksy dla literalnych liczb całkowitych ... '0x' jest prefiksem dla liczb _hexadecimal_. Prefiks, którego chcesz, to '0b'. –