Swap bits in a given number |  ; Setting bit at p1 position to 1 ; Setting bit at p2 position to 1 ; value1 and value2 will have 0 if num at the respective positions - p1 and p2 is 0. ; Check if value1 and value2 are different i . e . at one position bit is set and other it is not ; If bit at p1 position is set ; Unset bit at p1 position ; Set bit at p2 position ; If bit at p2 position is set ; Set bit at p2 position ; Unset bit at p2 position ; Return final result ; Driver code
function swapBits ( num , p1 , p2 , n ) { let shift1 , shift2 , value1 , value2 ; while ( n -- > 0 ) { shift1 = 1 << p1 ; shift2 = 1 << p2 ; value1 = ( ( num & shift1 ) ) ; value2 = ( ( num & shift2 ) ) ; if ( ( value1 == 0 && value2 != 0 ) || ( value2 == 0 && value1 != 0 ) ) { if ( value1 != 0 ) { num = num & ( ~ shift1 ) ; num = num | shift2 ; } else { num = num & ( ~ shift2 ) ; num = num | shift1 ; } } p1 ++ ; p2 ++ ; } return num ; } let res = swapBits ( 28 , 0 , 3 , 2 ) ; document . write ( " " + res ) ;