text: Swap bits in a given number | C 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 program to test above function
code: #include <stdio.h> NEW_LINE int swapBits ( unsigned int x , unsigned int p1 , unsigned int p2 , unsigned int n ) { unsigned int set1 = ( x >> p1 ) & ( ( 1U << n ) - 1 ) ; unsigned int set2 = ( x >> p2 ) & ( ( 1U << n ) - 1 ) ; unsigned int xor = ( set1 ^ set2 ) ; xor = ( xor << p1 ) | ( xor << p2 ) ; unsigned int result = x ^ xor ; return result ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 , 2 ) ; printf ( " Result = % d " , res ) ; return 0 ; }