How to count the number of bits to be flipped to convert N1 to N2 in Python

1 Answer

0 votes
def flipped_count(a , b):
    n = a ^ b
    count = 0
    while n:
        count += 1
        n &= (n-1)
        
    return count
 
 
a = 7
b = 10

print("a =", format(a, "04b"))
print("b =", bin(b)[2:])
print("a ^ b =", bin(a ^ b)[2:])
print(flipped_count(a, b))




'''
run:
 
a = 0111
b = 1010
a ^ b = 1101
3
 
'''

 



answered Dec 26, 2021 by avibootz
...