Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit efc36c1

Browse files
author
Ram swaroop
committed
swap even odd bits done
1 parent fae41b3 commit efc36c1

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/me/ramswaroop/bits/StrCmp.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public class StrCmp {
1111

1212
/**
1313
* Compares two strings {@param s1} and {@param s2} lexicographically ignoring case.
14-
* If both are equal, it returns 0 otherwise their lexicographic differences.
14+
* If both are equal it returns 0 otherwise their lexicographic differences.
1515
*
1616
* @param s1
1717
* @param s2

src/me/ramswaroop/bits/SwapBits.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,40 @@
99
*/
1010
public class SwapBits {
1111

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+
1246
/**
1347
* Swaps {@param length} bits in {@param n} starting from
1448
* {@param pos1} with bits starting from {@param pos2}.
@@ -38,6 +72,16 @@ public static int swapBitRangeInNumber(int n, int pos1, int pos2, int length) {
3872
}
3973

4074
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("-------------------------------");
4185
System.out.println(swapBitRangeInNumber(47, 1, 5, 3));
4286
System.out.println(swapBitRangeInNumber(28, 0, 3, 2));
4387
System.out.println(swapBitRangeInNumber(269, 1, 3, 2));

0 commit comments

Comments
 (0)