Bit Vectors (bitmaps) using C++

Bit Vectors or bitmaps are used to store data as a representation of bits. This can come in handy if you have memory constraints or you want to keep flags in your application and is mostly useful in game development nowadays.

I have created a sample implementation on how to implement bit vectors in C++. This is not the optimized code but the idea is to guide you on what is a bit vector and how it can be implemented.

I am using an array of unsigned char to create a bit vector. Since char has a standard size of 1 byte and since a byte has 8 bits we will use that to calculate the size required for the array.

SIZEOFARRAY

Once we have the size required, we will create the bit vector, In the below example I have taken a really large number to show you that it can be used on a large scale too.

CREATEVECTOR

Once the vector has been created, we should sanitize the memory so that all the bits are set to 0.

INITIALIZEVECTOR

To set the values at the desired location in the vector the below functions will be required, these functions calculate the byte to manipulate along with the exact bit and then set the value as required.

SETVALUE

To read the value stored at a position, following function can be used.

GETVALUE

That’s all for implementing a bit vector using unsigned char array. This is just a start as this has endless possibilities.

You can download the code here: BitVector