-1

我正在尝试在 C/C++ 中实现我自己对位标志的使用。我有三个函数:getBoolsetBoolprintBools。我当前的所有代码,除了一部分:我不能将位设置为假。他们设置为真就好了,他们读回就好了,但我不能将真位设置为假。这是我的代码:

#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 谢谢您的帮助!

4

1 回答 1

2

如果设置了该位,则返回:

if(getBool(boolSet, bit)) return;

所以你永远不能取消它们。

(但在实践中,最好使用 bitset 或使用|and进行掩码&- 为您节省检查步骤)

于 2015-12-13T06:02:50.630 回答