下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
下面是一些处理将标志存储为单个位的常见习惯用法。
enum CDRIndicators {
Local = 1 << 0,
External = 1 << 1,
CallerIDMissing = 1 << 2,
Chargeable = 1 << 3
};
unsigned int flags = 0;
设置Chargeable标志:
flags |= Chargeable;
清除CallerIDMissing标记:
flags &= ~CallerIDMissing;
测试CallerIDMissing和Chargeable是否设置:
if((flags & (CallerIDMissing | Chargeable )) == (CallerIDMissing | Chargeable)) {
}
其他回答
当我第一次开始C编程时,我理解了真值表和所有的东西,但直到我读了这篇文章http://www.gamedev.net/reference/articles/article1563.asp(它给出了真实的例子),我才完全了解如何实际使用它。
我经常使用位操作将选项的组合存储在一个整数中。
int options = 0;
其中OPTION1可以定义为1,OPTION2定义为2,OPTION3定义为4,OPTION4定义为8,OPTION5定义为16,…
void addOption(int option)将使用|操作符向options中添加一个选项。
boolean hasOption(int option)将使用&操作符来测试选项中的选项。
我一直假设按位操作是相当简单的操作,所以当运行时间至关重要时,通过bitset实现的解决方案可以通过恒定的数量提高运行时间,这取决于算法。
您可以使用它们作为一种快速而不常用的散列数据的方法。
int a = 1230123;
int b = 1234555;
int c = 5865683;
int hash = a ^ b ^ c;
我使用它们作为选项处理程序,例如在访问控制列表中描述特定的资源。
看看这篇文章http://planetozh.com/blog/2006/05/php-bitwise-operators-example-of-use/
Edit:还有一个链接: http://blog.code-head.com/how-to-write-a-permission-system-using-bits-and-bitwise-operations-in-php