Search code examples
pythonbit-manipulationbitwise-operatorsbit-shift

Flip the k-th significant bit


I would like to find a better way to achieve the following:

n = 6
k = 1

Flip the 1st significant bit in 6

Variable      Binary representation      Decimal Representation
       n                        110                           6
m(result)                       010                           2

I would like to achive the same as in this wiki article

Here is what I did, but I find it a bit overkill, an unefficient:

def toggleKthSignificantBit(self, n, k):
        tmp = list(bin(n)[2:].zfill(3))
        tmp[k-1] = str(int(tmp[k-1]) ^ 1)
        tmp2 = ''.join(tmp)
        print(tmp2)
        return int(tmp2, 2)

Solution

  • After doing some examination, I found a solution for my question:

    However, I think I find a equivalent solution:

    n ^ (2**(butterfly_rank - k))