C ++ bool array like bitfield?

let's say I need to store 8 bools in a structure, but I want to use only 1 byte for them 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 that I could do things like

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

How true is this? (I don’t know this actually, I have never used beatpods before)

ok - but it is also possible to create a static array of 8 bools, so that they will only use 8 bits, but can I still address them by index?

sort of

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

may be? (with this I get error message C2033)

thanks for the help!

+4
source share
4 answers

I would recommend using std::bitset this way you could just declare:

 std::bitset<8> asdf; 

and use it with [].

 asdf[0] = true; asdf[3] = false; 
+10
source

Wouldn't you use the byte data type to hold everything at once? Then you will need to use the logical AND and OR to get / paste material into it. No struct .

+1
source

For various reasons, I do not think this is a good idea - you are basically trying to reproduce the vector<bool> behavior, which turned out to be not a good idea . If you are trying to do this only to save memory, I would not worry. The overhead of accessing various bools and retrieving them from the bitfield is likely to be much higher than the small memory that you save, unless you are limited by memory restrictions.

To answer your direct question, if you want to execute the bool / bitfield command, you will have to use your first approach.

Usually the legal and accepted use of the bit-bit / bit-tweeter approach is when you have to deal with hardware registers and try to either simulate the hardware register or actually access the hardware registers, making it look like a memory location and overlapping bit structure over register.

0
source

You may be able to get your compiler to do what you want, but unfortunately this is not required. For example, even a good compiler that agrees with the above can ultimately allocate a 32-bit word for your myStruct objects.

If you have this option and you want this level of control over your types and how they are aligned and distributed, you should probably consider using Ada. For example, Ada works fine:

 type Bit_Set is array (1..8) of Boolean; for Bit_Set'size use 8; High_Mask : constant Bit_Set := (1..7 => false, 8 => true); 

... and now you have a single-byte bitmask, and the operators are "and", "or", "xor", etc. work bit by bit with him.

-one
source

All Articles