public class BitSwapper {
/**
* Prints the 8-bit binary representation of an integer.
*/
private static void printBinary8(int value) {
String binary = String.format("%8s", Integer.toBinaryString(value & 0xFF)).replace(' ', '0');
System.out.println(binary);
}
/**
* Swaps odd and even bits in a 32-bit integer.
*/
private static int swapOddAndEvenBits(int n) {
// (binary: 101010...) to isolate odd bits.
int oddBits = n & 0xAAAAAAAA;
// (binary: 010101...) to isolate even bits.
int evenBits = n & 0x55555555;
System.out.print("oddBits: ");
printBinary8(oddBits);
System.out.print("evenBits: ");
printBinary8(evenBits);
// Right-shift odd bits by 1 to move them to even positions.
oddBits >>>= 1;
// Left-shift even bits by 1 to move them to odd positions.
evenBits <<= 1;
System.out.print("oddBits Right-shift: ");
printBinary8(oddBits);
System.out.print("evenBits Left-shift: ");
printBinary8(evenBits);
// Combine shifted bits
return oddBits | evenBits;
}
public static void main(String[] args) {
int n = 90;
// Original number in binary
printBinary8(n);
int result = swapOddAndEvenBits(n);
// Final result in binary
printBinary8(result);
}
}
/*
run:
01011010
oddBits: 00001010
evenBits: 01010000
oddBits Right-shift: 00000101
evenBits Left-shift: 10100000
10100101
*/