How to swap two bits of a 32-bit integer number in Java

1 Answer

0 votes
public class MyClass {
    private static int swap_bits(int  num, int pos1, int pos2) {
        int result = ((num & (1 << pos1)) >> pos1) ^ ((num & (1 << pos2)) >> pos2);
        
        if (result != 0) {
            num ^= (1 << pos1);
            num ^= (1 << pos2);
        }
        
        return num;
    }
    
    public static void main(String args[]) {
        int number = 41337; // 0000000000000000101000010-1-111-0-01
        int pos1 = 2;
        int pos2 = 6;
      
        System.out.println(String.format("%32s", Integer.toBinaryString(number)).replaceAll(" ", "0"));
     
        int swaped_bits = swap_bits(number, pos1, pos2);
     
        System.out.println(String.format("%32s", Integer.toBinaryString(swaped_bits)).replaceAll(" ", "0"));
    }
}





/*
run:
    
00000000000000001010000101111001
00000000000000001010000100111101
    
*/

 



answered Dec 22, 2023 by avibootz

Related questions

1 answer 128 views
1 answer 177 views
1 answer 133 views
1 answer 110 views
1 answer 132 views
1 answer 132 views
...