File tree Expand file tree Collapse file tree 2 files changed +43
-3
lines changed Expand file tree Collapse file tree 2 files changed +43
-3
lines changed Original file line number Diff line number Diff line change
1
+ package me .ramswaroop .bits ;
2
+
3
+ /**
4
+ * Created by IntelliJ IDEA.
5
+ *
6
+ * @author: ramswaroop
7
+ * @date: 6/5/15
8
+ * @time: 4:26 PM
9
+ * @link http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c
10
+ * @link http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
11
+ */
12
+ public class ReverseBits {
13
+
14
+ public static int getNumberByReversingBits (int n ) {
15
+ System .out .println (Integer .toBinaryString (n ));
16
+
17
+ int m ;
18
+ // assume 32-bit number
19
+ m = 0x55555555 ; // 1-bit swap
20
+ n = ((n & m ) << 1 ) | ((n & ~m ) >> 1 );
21
+
22
+ m = 0x33333333 ; // 2-bits swap
23
+ n = ((n & m ) << 2 ) | ((n & ~m ) >> 2 );
24
+
25
+ m = 0x0f0f0f0f ; // 4-bits swap
26
+ n = ((n & m ) << 4 ) | ((n & ~m ) >> 4 );
27
+
28
+ m = 0x00ff00ff ; // 8-bits swap
29
+ n = ((n & m ) << 8 ) | ((n & ~m ) >> 8 );
30
+
31
+ n = (n << 16 ) | (n >> 16 ); // 16-bits swap
32
+
33
+ System .out .println (Integer .toBinaryString (n ));
34
+ return n ;
35
+ }
36
+
37
+ public static void main (String a []) {
38
+ System .out .println (getNumberByReversingBits (7 ));
39
+ }
40
+ }
Original file line number Diff line number Diff line change @@ -15,14 +15,14 @@ public class SubBit {
15
15
*
16
16
* @param num
17
17
* @param start > 0 and <= 32
18
- * @param end > 0 and <= 32
18
+ * @param end > 0 and <= 32
19
19
* @return
20
20
*/
21
- public static int getSubBits (int num , int start , int end ) {
21
+ public static int getNumberFromSubBits (int num , int start , int end ) {
22
22
return num << (32 - end ) >>> (start - end + 31 ); // more intuitive (start - 1 + 32 - end)
23
23
}
24
24
25
25
public static void main (String a []) {
26
- System .out .println (getSubBits (5 , 1 , 2 ));
26
+ System .out .println (getNumberFromSubBits (5 , 1 , 2 ));
27
27
}
28
28
}
You can’t perform that action at this time.
0 commit comments