fudo
fudo

Reputation: 2966

C++ bitmap to hold binary flags

the problem is this: I need to create a bitmap (a series of binary flags) to hold true/false information about a bunch of objects; the number of object is not known a priori so I have to allocate enough flags at runtime, possibly during the bitmap creation.

Given max_num_elements elements, my first idea was to allocate an array of ((num_elements/8)+1)*sizeof(char) bits: since a char is 8bit long it can handle 8 binary flags, so I get the minimun number of chars to hold num_elements flags, with a max memory waste of 7bits.

The real problem is for checking/setting the flags: I tought to do some bitshifting on the whole array followed by a bitwise and to get flag n like

flag_n = (flag_array>>n)&0d1

but if I understood correctly, the shifting operation won't afffect the whole array, just the first element.

How can I achieve this?

Upvotes: 2

Views: 717

Answers (1)

BoBTFish
BoBTFish

Reputation: 19767

std::vector<bool> is specialised to achieve exactly this.

It is actually a problem in many cases, since access to an element returns a proxy object rather than a bool&, so it doesn't quite behave like all the other containers, but it seems like in your case it suits what you need.

Upvotes: 1

Related Questions