C 位标志不能被取消设置

C bit flags cant be unset

我正在尝试在 C/C++ 中实现我自己对位标志的使用。我有三个函数:getBoolsetBoolprintBools。我当前的所有代码,除了一部分:我不能将位设置为假。他们设置为 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
}

此外,如果您想真正快速地查看输出,这里是 link:cpp.sh/6gpu 感谢您的帮助!

您 return 如果设置了该位:

if(getBool(boolSet, bit)) return;

因此您永远无法取消设置。

(但实际上最好使用 bitset,或使用 |& 进行屏蔽 - 省去检查步骤)