Swap bits in a given number | PHP Program to swap bits in a given number function returns the swapped bits ; Move all bits of first set to rightmost side ; Move 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
< ? php function swapBits ( $ x , $ p1 , $ p2 , $ n ) { $ set1 = ( $ x >> $ p1 ) & ( ( 1 << $ n ) - 1 ) ; $ set2 = ( $ x >> $ p2 ) & ( ( 1 << $ n ) - 1 ) ; $ xor = ( $ set1 ^ $ set2 ) ; $ xor = ( $ xor << $ p1 ) | ( $ xor << $ p2 ) ; $ result = $ x ^ $ xor ; return $ result ; } $ res = swapBits ( 28 , 0 , 3 , 2 ) ; echo " Result = " ? >