|
9 | 9 | */
|
10 | 10 | public class SwapBits {
|
11 | 11 |
|
| 12 | + /** |
| 13 | + * Swaps bits at even position with bits |
| 14 | + * at odd position in {@param n}. |
| 15 | + * |
| 16 | + * @param n |
| 17 | + * @return |
| 18 | + */ |
| 19 | + public static int swapEvenOddBits(int n) { |
| 20 | + int evenBits = n & 0x55555555; |
| 21 | + int oddBits = n & 0xaaaaaaaa; |
| 22 | + |
| 23 | + return evenBits << 1 | oddBits >> 1; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Swaps bits at even position with bits |
| 28 | + * at odd position in {@param n}. |
| 29 | + * |
| 30 | + * @param n |
| 31 | + * @return |
| 32 | + */ |
| 33 | + public static int swapEvenOddBits_V1(int n) { |
| 34 | + for (int i = 0; i < 32; i += 2) { |
| 35 | + int evenBit = (n >> i) & 1; |
| 36 | + int oddBit = (n >> (i + 1)) & 1; |
| 37 | + int xor = evenBit ^ oddBit; |
| 38 | + |
| 39 | + n ^= xor << i; |
| 40 | + n ^= xor << (i + 1); |
| 41 | + } |
| 42 | + return n; |
| 43 | + } |
| 44 | + |
| 45 | + |
12 | 46 | /**
|
13 | 47 | * Swaps {@param length} bits in {@param n} starting from
|
14 | 48 | * {@param pos1} with bits starting from {@param pos2}.
|
@@ -38,6 +72,16 @@ public static int swapBitRangeInNumber(int n, int pos1, int pos2, int length) {
|
38 | 72 | }
|
39 | 73 |
|
40 | 74 | public static void main(String a[]) {
|
| 75 | + System.out.println(swapEvenOddBits(23)); |
| 76 | + System.out.println(swapEvenOddBits(0)); |
| 77 | + System.out.println(swapEvenOddBits(5)); |
| 78 | + System.out.println(swapEvenOddBits(6)); |
| 79 | + System.out.println("-------------------------------"); |
| 80 | + System.out.println(swapEvenOddBits_V1(23)); |
| 81 | + System.out.println(swapEvenOddBits_V1(0)); |
| 82 | + System.out.println(swapEvenOddBits_V1(5)); |
| 83 | + System.out.println(swapEvenOddBits_V1(6)); |
| 84 | + System.out.println("-------------------------------"); |
41 | 85 | System.out.println(swapBitRangeInNumber(47, 1, 5, 3));
|
42 | 86 | System.out.println(swapBitRangeInNumber(28, 0, 3, 2));
|
43 | 87 | System.out.println(swapBitRangeInNumber(269, 1, 3, 2));
|
|
0 commit comments