Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a bit-array in C++?

What's the best way to store a bit array in C++ (no Boost, just standard containers), representing, for example, a volume allocation bitmap?

I thought std::vector<bool> was a great idea, but apparently it's Evil and deprecated, so is there a better choice?

Also:

If I have a byte array in memory, how would I go about copying them to the recommended container?
(I'm having trouble figuring this out for vector<bool>.)

like image 790
user541686 Avatar asked Oct 20 '11 00:10

user541686


2 Answers

The std::bitset will do, as long as your bit array is of fixed size.
As a side note there's also std::dynamic_bitset, but am not 100% sure it made it into the standard.

like image 86
Eugen Constantin Dinca Avatar answered Oct 06 '22 07:10

Eugen Constantin Dinca


For vanilla C++, there's std::bitset.

Bitset is very similar to vector (also known as bit_vector): it contains a collection of bits, and provides constant-time access to each bit. There are two main differences between bitset and vector. First, the size of a bitset cannot be changed: bitset's template parameter N, which specifies the number of bits in the bitset, must be an integer constant. Second, bitset is not a Sequence; in fact, it is not an STL Container at all.

Matt Austern has a nice article on its use.

Also: If your byte array (bit array?) fits into an unsigned long, then you can assign it to a std::bitset directly:

unsigned long myByteArray = 0xABCD;
std::bitset<32> bitten( myByteArray );
like image 38
Gnawme Avatar answered Oct 06 '22 08:10

Gnawme