0%

二进制位运算

运算符

按位与(&)

1&3 = 1 // 0001 & 0011 = 0001

按位或(|)

9|3=11 // 1001 & 0011 = 1011

按位异或(^)

9^3 = 10 // 1001 & 0011 == 1010

按位非(~)

1; // 二进制 00000000000000000000000000000001

~1 = 111111111111111111111111111110

有符号左移(<<)

1 << 1 = 2 // 00000000000000000000000000000001<<1 = 00000000000000000000000000000010

-1 << 1 = - 2 // 111111111111111111111111111111 << 1 = 111111111111111111111111111110

有符号右移(>>)

1 >> 1 = 0 // 00000000000000000000000000000001 >>1 = 00000000000000000000000000000000

-2>>1 = -1 //111111111111111111111111111110 >> 1 = 111111111111111111111111111111

-1>>1 = -1 // 111111111111111111111111111110 >> 1 = 111111111111111111111111111111

应用场景

判断一个节点在一个八分空间中的位置

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
switch (i = (z < (z0 + z1 / 2)) << 2 | (y < (y0 + y1) / 2) << 1 | (x < (x0 + x1) / 2)) {
case 0: {
//do something
break;
}
case 1: {
//do something
break;
}
case 2: {
//do something
break;
}
case 3: {
//do something
break;
}
case 4: {
//do something
break;
}
case 5: {
//do something
break;
}
case 6: {
//do something
break;
}
case 7: {
//do something
break;
}
}