How to swap two bits in a given integer ? | Java code for swapping given bits of a number ; left - shift 1 p1 and p2 times and using XOR ; Driver code
import java . util . * ; class Main { public static int swapBits ( int n , int p1 , int p2 ) { n ^= 1 << p1 ; n ^= 1 << p2 ; return n ; } public static void main ( String [ ] args ) { System . out . print ( " Result ▁ = ▁ " + swapBits ( 28 , 0 , 3 ) ) ; } }