c语言中&,|位运算符

与运算(&),是一个双目运算符,二个值都等于1时,结果等于1,其它的结果都等于0,按位与总会计算两个表达式的值

1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0

或运算(|),

value = 1|1; //1

value = 1|0; //1

value = 0|1; //1

value = 0|0; //0

&与| 既可以进行逻辑运算,又可以进行位运算,两边既可以是bool类型,又可以是数值类型,& | 为整型和 bool 类型预定义了两种运算规则,对于整型,& 和 | 计算操作数的按位“与”;对于 bool 操作数,& 或 | 计算操作数的逻辑“与”、“或”;对于整形数据&两边的数据则进行按位与运算,并返回计算结果让if判断这个值


#include<iostream>
using namespace std;
struct SafetyEventState {
    enum State {
		BREAK_ESCAPE = 0,//0000
        STOP = 1,//0001
        BLOCK_FRONT = 2,//0010
        BLOCK_BACK = 4,//0100
        BLOCK_LEFT = 8,//1000
        BLOCK_RIGHT = 16,//10000
        LIMIT = 32,//100000
        HOLD = 64//1000000
    };
};
int main()
{
unsigned int state = SafetyEventState::BLOCK_FRONT | SafetyEventState::BLOCK_BACK | SafetyEventState::BLOCK_LEFT | SafetyEventState::BLOCK_RIGHT;//或运算
//0010|0100=0110,  0110|1000=1110, 1110|10000=11110=16+8+4+2=30
cout<<state<<endl;//30,
int value = 1 & 1;    //1,与运算
cout<<value<<endl;
int all_state=2;
cout<<(all_state&state)<<endl;//0010&11110=00010=2
if(all_state&state)//因为是2,所以为真
{
	cout<<(all_state&state)<<endl;
}
return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_38145317/article/details/84528608