How to swap two bits in a given integer ? | This function swaps bit at positions p1 and p2 in an integer n ; Move p1 'th to rightmost side ; Move p2 'th to rightmost side ; XOR the two bits ; Put the xor bit back to their original positions ; XOR ' x ' with the original number so that the two sets are swapped ; Driver program to test above function
def swapBits ( n , p1 , p2 ) : NEW_LINE INDENT bit1 = ( n >> p1 ) & 1 NEW_LINE bit2 = ( n >> p2 ) & 1 NEW_LINE x = ( bit1 ^ bit2 ) NEW_LINE x = ( x << p1 ) | ( x << p2 ) NEW_LINE result = n ^ x NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT res = swapBits ( 28 , 0 , 3 ) NEW_LINE print ( " Result ▁ = ▁ " , res ) NEW_LINE DEDENT