How to swap two bits in a given integer ? | Java program to swap bits in an 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
import java . io . * ; class GFG { static int swapBits ( int n , int p1 , int p2 ) { int bit1 = ( n >> p1 ) & 1 ; int bit2 = ( n >> p2 ) & 1 ; int x = ( bit1 ^ bit2 ) ; x = ( x << p1 ) | ( x << p2 ) ; int result = n ^ x ; return result ; } public static void main ( String [ ] args ) { int res = swapBits ( 28 , 0 , 3 ) ; System . out . println ( " Result ▁ = ▁ " + res ) ; } }