-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathBitUtil.java
More file actions
51 lines (43 loc) · 1.24 KB
/
BitUtil.java
File metadata and controls
51 lines (43 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package ssj.algorithm.math;
import com.google.common.base.Preconditions;
/**
* Created by shenshijun on 15/2/10.
*/
public class BitUtil {
private BitUtil() {
}
/**
* 比较一个位置的位是不是1
*
* @param value 要判断的值
* @param index 从右开始计数
* @return
*/
public static boolean testBit(long value, int index) {
Preconditions.checkArgument(index >= 0 && index < Long.SIZE);
return (value & (1L << index)) != 0;
}
public static int firstBitOne(long value) {
for (int i = 0; i < Integer.SIZE; i++) {
if (BitUtil.testBit(value, i)) {
return i;
}
}
return -1;
}
public static long moveBit(long value, int from, int to) {
int clear_mask = ~(1 << from);
int set_mask = 1 << to;
return (value & clear_mask) | set_mask;
}
public static int diffBit(long one, long other) {
int count = 0;
for (long c = one ^ other; c != 0; c = c >> 1) {
count += (c & 1L);
}
return count;
}
public static long swapBit(long value) {
return (((value & 0xaaaaaaaaaaaaaaaaL) >> 1) | ((value & 0x5555555555555555L) << 1));
}
}