Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ bool array as bitfield?

let's say i need to store 8 bools in a struct, but i want to use for them only 1 byte together, then i could do something like this:

struct myStruct {
    bool b1:1;
    bool b2:1;
    bool b3:1;
    bool b4:1;
    bool b5:1;
    bool b6:1;
    bool b7:1;
    bool b8:1;
};

and with this i could do things like

myStruct asdf;
asdf.b3=true;
asdf.b4=false;
if(asdf.b1)
    ...

is this correct so far? (i don't know it actually, i never used bitfields before)

ok - but is it also possible to create a static array of 8 bools such that they will use only 8 bits but i will still be able to adress them by index?

something like

struct myStruct {
public:
    bool b[8]:8;
};

maybe? (with this, i get a error C2033)

thanks for the help!

like image 315
Mat Avatar asked Dec 29 '22 10:12

Mat


1 Answers

I would recommend using a std::bitset That way you could simply declare:

std::bitset<8> asdf;

and use it with [].

asdf[0] = true;
asdf[3] = false;
like image 93
Dan Hook Avatar answered Jan 11 '23 10:01

Dan Hook