下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
当你只想改变微控制器输出的一些位,但要写入的寄存器是一个字节时,你可以这样做(伪代码):
char newOut = OutRegister & 0b00011111 //clear 3 msb's
newOut = newOut | 0b10100000 //write '101' to the 3 msb's
OutRegister = newOut //Update Outputs
当然,许多微控制器允许你单独改变每一位。
其他回答
按位&用于屏蔽/提取字节的某一部分。
1字节变量
01110010
&00001111 Bitmask of 0x0F to find out the lower nibble
--------
00000010
特别是移位运算符(<< >>)经常用于计算。
我将它们用于多选择选项,这样我只存储一个值,而不是10个或更多
这是一个从字节格式的位图图像中读取颜色的例子
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.
我希望这个小例子可以帮助....
我使用它们作为选项处理程序,例如在访问控制列表中描述特定的资源。
看看这篇文章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
我曾在一些游戏开发书籍中看到它是一种更有效的乘除方法。
2 << 3 == 2 * 8
32 >> 4 == 32 / 16