Sólo se necesita:
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
Tenga en cuenta que los números se mordió (index
) son de 0, donde 0 es el bit menos significativo.
También tenga en cuenta que el nuevo valor es devuelto, no hay forma de modificar un entero "en su lugar" como se muestra (al menos no lo creo).
Al igual que en C. http://wiki.python.org/moin/BitwiseOperators – Kos
Tenga cuidado con sus prefijos para enteros literales ... '0x' es el prefijo para los números _hexadecimal_. El prefijo que quieres es '0b'. –