下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
我使用它们作为选项处理程序,例如在访问控制列表中描述特定的资源。
看看这篇文章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
其他回答
低级编程就是一个很好的例子。例如,你可能需要写一个特定的位到内存映射寄存器,以使某些硬件做你想要它做的事情:
volatile uint32_t *register = (volatile uint32_t *)0x87000000;
uint32_t value;
uint32_t set_bit = 0x00010000;
uint32_t clear_bit = 0x00001000;
value = *register; // get current value from the register
value = value & ~clear_bit; // clear a bit
value = value | set_bit; // set a bit
*register = value; // write it back to the register
同样,htonl()和htons()是使用&和|操作符实现的(在字节顺序不匹配网络顺序的机器上):
#define htons(a) ((((a) & 0xff00) >> 8) | \
(((a) & 0x00ff) << 8))
#define htonl(a) ((((a) & 0xff000000) >> 24) | \
(((a) & 0x00ff0000) >> 8) | \
(((a) & 0x0000ff00) << 8) | \
(((a) & 0x000000ff) << 24))
一个常见的用法是对齐,例如我需要我的数据在4字节或16字节的边界上对齐。这在RISC处理器中非常常见,其中未对齐的加载/存储要么代价高昂(因为它触发了一个异常处理程序,然后需要修复未对齐的加载),要么根本不允许。
对于任何以2为幂的对齐,下一个对齐的pos可以计算如下:
aligned_offset = alignment + ((current_offset - 1) & ~(alignment - 1))
所以在4字节对齐和当前偏移量为9的情况下:
aligned_offset = 4 + ((9-1) & ~(4-1)) = 4 + (8 & 0xFFFFFFFC) = 4+ 8 = 12
所以下一个4字节的对齐偏移量是12
我将它们用于多选择选项,这样我只存储一个值,而不是10个或更多
您可以使用它们作为一种快速而不常用的散列数据的方法。
int a = 1230123;
int b = 1234555;
int c = 5865683;
int hash = a ^ b ^ c;
这是一个从字节格式的位图图像中读取颜色的例子
byte imagePixel = 0xCCDDEE; /* Image in RRGGBB format R=Red, G=Green, B=Blue */
//To only have red
byte redColour = imagePixel & 0xFF0000; /*Bitmasking with AND operator */
//Now, we only want red colour
redColour = (redColour >> 24) & 0xFF; /* This now returns a red colour between 0x00 and 0xFF.
我希望这个小例子可以帮助....