c语言位运算
1.按为与(&)运算
按位于算一般用于将某些位设置为零,而其余位保持不变
//位运算,获取n的第bit为的二进制位 bit从0开始,将n向右移位bit位与1进行与运算
int getBinary_bit(const int n,int bit){
return 1&(n>>bit); //或者 n&(1<<bit)==1<<bit;
}
//设置n的第bit二进制位零,其余位保持不变
int setBinary_posZero(const int n,int bit){
return n&(~(1<<bit));
}
//设置n的第bit二进制位零,其余位保持不变
int setBinary_posZero(const int n,int bit){
return n&(~(1<<bit));
}
//设置n的低bit二进制位为零,其余位保存不变相当于
int setBinary_lowbitZero(const int n,int bit){
return n&(0xffffffff<<bit);
}
2.按位或(|)运算
按位或运算(|)一般用于将某些位设置为1,而其余位保持不变
//设置n的第bit位二进制为1
int setBinary_posbitOne(const int n,int bit){
return n|(1<<bit);
}
//设置n的低bit为二进制位为1
int setBinary_lowbitOne(const int n,int bit){
//n|0xff 低8为全部设置为1
return n|(~(1<<(bit+1)));
}
3.按位异或(^)预算一般用于将某些位取反,而其他的位保持不变
//将n的低bit位取反
int reverseBinary_lowbit(const int n,int bit){
return n^(~(1<<(bit+1)));
}
//将n的第bit位取反
int reverseBinary_posbit(const int n,int bit){
return n^(1<<bit);
}