C++| -按位或
示例
int a = 5; //0101b(0x05) int b = 12; //1100b(0x0C) int c = a | b; //1101b(0x0D) std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
输出结果
a=5,b=12,c=13
为什么
按位OR操作在位级别上使用以下布尔真值表:
true OR true = true true OR false = true false OR false = false
当二进制值a(0101)和二进制值b(1100)是OR“编在一起,我们得到的二进制值1101:
int a = 0 1 0 1 int b = 1 1 0 0 | --------- int c = 1 1 0 1
逐位或不会更改原始值的值,除非专门指定使用逐位分配复合运算符|=:
int a = 5; //0101b(0x05) a |= 12; //a=0101b|1101b