Skip to content

Commit 4381b4d

Browse files
author
Ram swaroop
committed
swap bit range done
1 parent 7c204e9 commit 4381b4d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/me/ramswaroop/bits/SwapBits.java

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package me.ramswaroop.bits;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 6/13/15
8+
* @time: 4:45 PM
9+
*/
10+
public class SwapBits {
11+
12+
/**
13+
* Swaps {@param length} bits in {@param n} starting from
14+
* {@param pos1} with bits starting from {@param pos2}.
15+
* <p/>
16+
* For example,
17+
* x = 28 (11100)
18+
* p1 = 0 (Start from first bit from right side)
19+
* p2 = 3 (Start from 4th bit from right side)
20+
* l = 2 (No of bits to be swapped)
21+
* Output:
22+
* 7 (00111)
23+
*
24+
* @param n
25+
* @param pos1 starts from 0
26+
* @param pos2 starts from 0
27+
* @param length
28+
* @return
29+
*/
30+
public static int swapBitRangeInNumber(int n, int pos1, int pos2, int length) {
31+
int set1 = (n >> pos1) & ((1 << length) - 1); // 1st set of bits to be swapped
32+
int set2 = (n >> pos2) & ((1 << length) - 1); // 2nd set of bits to be swapped
33+
int xor = set1 ^ set2; // difference pattern between the bits to be swapped
34+
35+
return n ^ (xor << pos1) ^ (xor << pos2); // XORing the difference pattern at the appropriate
36+
// position of the bits to be swapped gives us the result
37+
// (this logic is similar to swapping bits using XOR)
38+
}
39+
40+
public static void main(String a[]) {
41+
System.out.println(swapBitRangeInNumber(47, 1, 5, 3));
42+
System.out.println(swapBitRangeInNumber(28, 0, 3, 2));
43+
System.out.println(swapBitRangeInNumber(269, 1, 3, 2));
44+
}
45+
}

0 commit comments

Comments
 (0)