按位运算符的低级应用是进行二进制数学运算。有一个众所周知的技巧,可以测试一个数字是否为2的幂:
if ((x & (x - 1)) == 0) {
printf("%d is a power of 2\n", x);
}
然而,它也可以用于更高级的功能:集合操作。您可以将一组位视为一个集合。举个例子,让每个字节中的位表示8个不同的项,比如我们太阳系中的行星(冥王星不再被认为是行星,所以8位就足够了!):
然后,我们可以像使用|
一样形成行星的集合(子集):
unsigned char Giants = (Jupiter|Saturn|Uranus|Neptune);
unsigned char Visited = (Venus|Earth|Mars);
unsigned char BeyondTheBelt = (Jupiter|Saturn|Uranus|Neptune);
unsigned char All = (Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune);
现在,您可以使用&
来测试两个集合是否有交集:
if (Visited & Giants) {
puts("we might be giants");
}
通常使用 ^
运算符来查看两个集合之间的差异(集合的并集减去交集):
if (Giants ^ BeyondTheBelt) {
puts("there are non-giants out there");
}
因此,将|
视为并集,&
视为交集,将^
视为除去交集的并集。
一旦您接受了位表示集合的想法,那么按位操作自然就可以帮助您操作这些集合。