一些位运算

本文共172字。
Copyright: 知识共享署名 非商业性使用 相同方式共享 4.0 国际许可协议 | CC BY-NC-SA 4.0
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
52
// pos >= 0, from right
static int getBit(int num, int pos) {
return (num >> pos) & 1;
}

static int getHighestBitOne(int num) {
int pos = -1;
while (num > 0) {
++pos;
num >>= 1;
}
return pos;
}

static int setBit(int num, int pos, int to) {
if (to == 1) {
num |= (1 << pos);
} else if (to == 0) {
num &= ~(1 << pos);
}
return num;
}


// Example to = 0, num = 0b1001011:
// n = 0 : 1001011
// n = 1 : 1001010
// n = 2 : 1001000
// n = 3 : 1001000
// n = 4 : 1000000
// n = 5 : 1000000
// n = 6 : 1000000
// n = 7 : 0000000
//
// Example to = 1, num = 0b1001011:
// n = 0 : 1001011
// n = 1 : 1001011
// n = 2 : 1001011
// n = 3 : 1001111
// n = 4 : 1001111
// n = 5 : 1011111
// n = 6 : 1111111
// n = 7 : 1111111
static int setNBits(int num, int n, int to) {
if (to == 1) {
num |= (1 << n) - 1;
} else if (to == 0) {
num &= -(1 << n);
}
return num;
}