C/C++ で独自のビット フラグの使用を実装しようとしています。getBool、 、 の3 つの関数がsetBoolありprintBoolsます。一部を除く現在のコードのすべて: ビットを false に設定できません。それらは問題なく true に設定され、問題なく読み戻されますが、true ビットを 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
}
さらに、出力をすぐに確認したい場合は、次のリンクを参照してください: cpp.sh/6gpuご協力 ありがとうございます。