I am trying to implement my own use of bit flags in C/C++. I have three functions: getBool
, setBool
, and printBools
. All of my current code except one part: I can't set bits to false. They set to true just fine, they read back just fine, but I can't set true bits to false. Here is my code:
#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
}
Additionally, if you would like to see the output really quickly, here is a link: cpp.sh/6gpu Thank you for your help!