Swap bits in a given number | Javascript Program to swap bits in a given number ; 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
function swapBits ( x , p1 , p2 , n ) { let set1 = ( x >> p1 ) & ( ( 1 << n ) - 1 ) ; let set2 = ( x >> p2 ) & ( ( 1 << n ) - 1 ) ; let xor = ( set1 ^ set2 ) ; xor = ( xor << p1 ) | ( xor << p2 ) ; let result = x ^ xor ; return result ; } let res = swapBits ( 28 , 0 , 3 , 2 ) ; document . write ( " " + res ) ;