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
#include <iostream> NEW_LINE using namespace std ; int swapBits ( unsigned int num , unsigned int p1 , unsigned int p2 , unsigned int n ) { int shift1 , shift2 , value1 , value2 ; while ( n -- ) { shift1 = 1 << p1 ; shift2 = 1 << p2 ; value1 = ( ( num & shift1 ) ) ; value2 = ( ( num & shift2 ) ) ; if ( ( ! value1 && value2 ) || ( ! value2 && value1 ) ) { if ( value1 ) { num = num & ( ~ shift1 ) ; num = num | shift2 ; } else { num = num & ( ~ shift2 ) ; num = num | shift1 ; } } p1 ++ ; p2 ++ ; } return num ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 , 2 ) ; cout << " Result ▁ = ▁ " << res ; return 0 ; }