Question

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!

Was it helpful?

Solution

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;

OTHER TIPS

Wouldn't you rather use a byte data type to hold everything at once? Then you'd only have to use logical ANDs and ORs to get/put stuff into it. No struct required.

For various reasons I don't think it's a good idea - you're basically trying to replicate the behaviour of vector<bool> which has proven to be not a good idea. If you're trying to do this only to save memory, I wouldn't bother. The overhead of accessing the various bools and extracting them from a bit field is likely to be a lot higher than what little memory you save unless you're extremely constrained by memory limits.

To answer your direct question, if you want to do the bool/bitfield thing you'll have to use your first approach.

Normally the legitimate and accepted use for the bitfield/bit twiddling approach is when you have to deal with hardware registers and are trying to either model a hardware register or actually access a hardware register after making it look like a memory location and superimposing a bit field structure over the register.

You may be able to get your compiler to do what you want, but sadly it isn't required. For example, even a nice compiler that accepts the above might end up allocating an entire 32-bit word for your myStruct objects.

If you have the option, and you want that level of control over your types and how they are aligned and allocated, you should probably consider using Ada. For example, the following works just fine in Ada:

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 you now have a single-byte bitmask, and the operators "and", "or", "xor", etc. that work bitwise with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top