-4

可能重复:
位运算符的真实世界用例

我不太确定按位运算符&and |,有人可以向我解释这些运算符到底是做什么的吗?我昨天在http://www.cprogramming.com/tutorial/bitwise_operators.html阅读了教程,但是我真的不知道我是否想将它应用到编码中,有人可以举一些例子。

4

2 回答 2

0

运算符|(OR):

----------------------
 0000 1110 1110 0101
----------------------
 b 1001 0011 0100 1001
----------------------
a|b 1001 1111 1110 1101

运营商给出1是否1在其中一个数字中的位置。

运算符&(AND):

----------------------
 0000 1110 1110 0101
----------------------
 b 1001 0011 0100 1001
----------------------
a&b 0000 0010 0100 0001

运算符在其中一个数字中给出0if。

用法:如果我只想要数字的一部分(比如说第二组四个),我可以写:

a & 0x00f0

建议初学者使用位运算符。

于 2012-09-14T07:13:32.980 回答
0

这是一个非常低级的编程问题。最小的内存位是“位”。一个字节是一个 8 位的块,一个字是一个 16 位的块,依此类推……按位运算符让您可以更改/检查这些块的位。根据您为您编写的代码,您可能永远不需要这些运算符。

例子:

unsigned char x = 10; /*This declares a byte and sets it to 10. The binary representation
                        of this value is 00001010. The ones and zeros are the bits.*/

if (x & 2) {
  //Number 2 is binary 00000010, so the statements within this condition will be executed 
  //if the bit #1 is set (bits are numbered from right to left starting from #0) 
}

unsigned char y = x | 1; //This makes `y` equal to x and sets the bit #0. 
                         //I.e. y = 00001010 | 00000001 = 00001011 = 11 decimal
于 2012-09-14T07:14:06.783 回答