C++ 不能取消设置C位标志
我试图在C/C++中实现我自己对位标志的使用。我有三个函数:C++ 不能取消设置C位标志,c++,bitflags,C++,Bitflags,我试图在C/C++中实现我自己对位标志的使用。我有三个函数:getBool、setBool和printBools。我当前所有的代码除了一部分:我不能将位设置为false。它们很好地设置为真,很好地读回,但我不能将真位设置为假。这是我的密码: #include <iostream> #define uint unsigned int #define BIT1 1 #define BIT2 2 #define BIT3 4 #define BIT4 8 #define TRUE 1 #
getBool
、setBool
和printBools
。我当前所有的代码除了一部分:我不能将位设置为false。它们很好地设置为真,很好地读回,但我不能将真位设置为假。这是我的密码:
#include <iostream>
#define uint unsigned int
#define BIT1 1
#define BIT2 2
#define BIT3 4
#define BIT4 8
#define TRUE 1
#define true 1
#define FALSE 0
#define false 0
int getBool(uint boolSet, uint bit){
return ((boolSet&bit)==bit);
}
void setBool(uint &boolSet, uint bit, short tf){
if(getBool(boolSet, bit)) return;
else if(tf == 1) boolSet += bit;
else if(tf == 0) boolSet -= bit;
}
void printBools(uint boolSet, uint j){
uint i = 1, count = 1;
while(count <= j){
std::cout<<"Bool "<<count<<": "<<getBool(boolSet, i)<<std::endl;
i*=2;
count++;
}
}
int main(){
uint boolSet = 0;
printBools(boolSet, 4); //make sure bits are false
setBool(boolSet, BIT1, 1); //set bit 1 to true
setBool(boolSet, BIT3, 1); //set bit 3 to true
printBools(boolSet, 4); //check set bits
setBool(boolSet, BIT3, 0); //set bit 3 to false
setBool(boolSet, BIT4, 1); //set bit 4 to true
printBools(boolSet, 4); //check set bits
}
#包括
#定义uint unsigned int
#定义位1
#定义比特2
#定义比特3和比特4
#定义比特4和比特8
#定义真1
#定义真1
#定义FALSE 0
#定义false 0
int getBool(uint boolSet,uint bit){
返回((布尔集和位)=位);
}
无效设置工具(uint和boolSet、uint位、短tf){
if(getBool(boolSet,bit))返回;
如果(tf==1)boolSet+=bit,则为else;
如果(tf==0)boolSet-=位,则为else;
}
无效打印布尔(uint boolSet,uint j){
uint i=1,计数=1;
while(count如果设置了位,则返回:
if(getBool(boolSet, bit)) return;
所以你永远不能让他们不安
(但在实践中,最好使用位集,或者使用|
和&
掩蔽-节省检查步骤)ahhh,我刚刚更改为if(getBool(boolSet,bit)==tf)return
,现在它可以工作了,谢谢!