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
*/