数字可以用二进制表示,如下所示:
3 = 000011
5 = 000101
10 = 001010
...等等,我假设你熟悉二进制.
按位AND表示取两个数字,将它们排成一行,然后创建一个新的数字,其中两个数字都有一个1(其他所有数字都是0).
例如:
3 => 00011
& 5 => 00101
------ -------
1 00001
按位或意味着取两个数字,将它们排成一行,然后创建一个新的数字,其中任何一个数字都有一个1(其他所有数字都是0).
例如:
3 => 00011
| 5 => 00101
------ -------
7 00111
按位异或(异或)意味着取两个数字,将它们排列在一起,创建一个新的数字,其中一个数字有一个1,另一个数字有一个0(其他所有数字都是0).
例如:
3 => 00011
^ 5 => 00101
------ -------
6 00110
按位NOR(Not OR)表示取两个数字的按位OR,然后反转所有数字(如果有0,现在有1,如果有1,现在有0).
按位与非门(Not AND)意味着取两个数字的按位与非门,然后反转所有数字(在有0的地方,现在有1,在有1的地方,现在有0).
继续:为什么word &= 15
将除最右边的4位之外的所有位都设置为0?你现在应该能弄明白了...
n => abcdefghjikl
& 15 => 000000001111
------ --------------
? 00000000jikl
(0 AND a = 0
, 0 AND b = 0
, ... j AND 1 = j
, i AND 1 = i
, ...)
How is this useful? In many languages, we use things called "bitmasks". A bitmask is essentially a number that represents a whole bunch of smaller numbers combined together. We can combine numbers together using OR, and pull them apart using AND. 例如:
int MagicMap = 1;
int MagicWand = 2;
int MagicHat = 4;
如果我只有 map 和帽子,我可以表示为myInventoryBitmask = (MagicMap | MagicHat)
,结果就是我的位掩码.如果我什么都没有,那么我的位掩码是0.如果我想看看我是否有魔杖,那么我可以:
int hasWand = (myInventoryBitmask & MagicWand);
if (hasWand > 0) {
printf("I have a wand\n");
} else {
printf("I don't have a wand\n");
}
了解了?
编辑:更多内容
You'll also come across the "bitshift" operator: << and >>. This just means "shift everything left n bits" or "shift everything right n bits".
换句话说:
1 << 3
= 0001 << 3
= 0001000
= 8
以及:
8 >> 2
= 01000 >> 2
= 010
= 2