按位 AND
int a = 6; // 0110b (0x06)
int b = 10; // 1010b (0x0A)
int c = a & b; // 0010b (0x02)
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
输出
a = 6, b = 10, c = 2
为什么
有点明智的 AND
在位级操作并使用以下布尔真值表:
TRUE AND TRUE = TRUE
TRUE AND FALSE = FALSE
FALSE AND FALSE = FALSE
当 a
(0110
)的二进制值和 b
(1010
)的二进制值是 AND
‘时,我们得到 0010
的二进制值:
int a = 0 1 1 0
int b = 1 0 1 0 &
---------
int c = 0 0 1 0
除非特别指定使用按位分配复合运算符 &=
,否则按位 AND 不会更改原始值的值:
int a = 5; // 0101b (0x05)
a &= 10; // a = 0101b & 1010b