Going by the examples provided, it sounds like you are looking to swap bits in an integer.
For example in 7 (0b00000111)
, if you swap the bits in the 3rd and 1st positions you obtain 13 (0b00001101)
.
I would have the following as a function signature swap_bits(val, i, j)
What is the best algorithm? Well, the following algorithm takes constant time, O(1).
def swap_bits(val, i, j):
"""
Given an integer val, swap bits in positions i and j if they differ
by flipping their values, i.e, select the bits to flip with a mask.
Since v ^ 1 = 0 when v = 1 and 1 when v = 0, perform the flip using an XOR.
"""
if not (val >> i) & 1 == (val >> j) & 1:
mask = (1 << i) | (1 << j)
val ^= mask
return val
Example:
>>> swap_bits(7, 3, 1)
13
The code leverage bit twiddling tricks and here is a good resource by Sean Anderson. I am working on providing the code snippets in Python here.