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 code
function swapBits ( n , p1 , p2 ) { var bit1 = ( n >> p1 ) & 1 ; var bit2 = ( n >> p2 ) & 1 ; var x = ( bit1 ^ bit2 ) ; x = ( x << p1 ) | ( x << p2 ) ; var result = n ^ x ; return result ; } var res = swapBits ( 28 , 0 , 3 ) ; document . write ( " " + res ) ;