How to modify bits in an integer?

Váradi Norbert picture Váradi Norbert · Aug 29, 2012 · Viewed 38.9k times · Source

I have an integer with a value 7 (0b00000111) And I would like to replace it with a function to 13 (0b00001101). What is the best algorithm to replace bits in an integer?

For example:

set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?

Answer

Kos picture Kos · Aug 29, 2012

These work for integers of any size, even greater than 32 bit:

def set_bit(value, bit):
    return value | (1<<bit)

def clear_bit(value, bit):
    return value & ~(1<<bit)

If you like things short, you can just use:

>>> val = 0b111
>>> val |= (1<<3)
>>> '{:b}'.format(val)
'1111'
>>> val &=~ (1<<1)
'1101'