Swap bits in a given number | Python program to swap bits in a given number ; Move all bits of first set to rightmost side ; Moce all bits of second set to rightmost side ; XOR the two sets ; Put the xor bits back to their original positions ; XOR the ' xor ' with the original number so that the two sets are swapped ; Driver code
def swapBits ( x , p1 , p2 , n ) : NEW_LINE INDENT set1 = ( x >> p1 ) & ( ( 1 << n ) - 1 ) NEW_LINE set2 = ( x >> p2 ) & ( ( 1 << n ) - 1 ) NEW_LINE xor = ( set1 ^ set2 ) NEW_LINE xor = ( xor << p1 ) | ( xor << p2 ) NEW_LINE result = x ^ xor NEW_LINE return result NEW_LINE DEDENT res = swapBits ( 28 , 0 , 3 , 2 ) NEW_LINE print ( " Result ▁ = " , res ) NEW_LINE