Posted by: Cirilo Meggiolaro | 10/24/2008

Tip of the day #10 – Store boolean flags and small integers in just one…BitVector32

Today’s tip is something that you will not see often but it’s really interesting.

Anyway, I really enjoy the fact we can store boolean values and small integers in a single structure with 32 bits of memory.

The BitVector32 (available under System.Collections.Specialized namespace) structure is the simple way to store either small integers or boolean flags (not at the same time).

BitVector32 myBitVector = new BitVector32();

How do you store integers?

You have to create sections in the BitVector32 structure that determine the number of bits for each small integer stored and the sequence that the values will be stored.

BitVector32.Section mySection1 = BitVector32.CreateSection(10);
BitVector32.Section mySection2 = BitVector32.CreateSection(20, mySection1);
BitVector32.Section mySection3 = BitVector32.CreateSection(35, mySection2);
BitVector32.Section mySection4 = BitVector32.CreateSection(100, mySection3);

myBitVector[mySection1] = 10;
myBitVector[mySection2] = 20;
myBitVector[mySection3] = 30;
myBitVector[mySection4] = 87;

How do you store booleans?

To store boolean values you should create masks. The mask acts as the indexer of the BitVector32 structure.

int mask1 = BitVector32.CreateMask();
int mask2 = BitVector32.CreateMask(mask1);
int mask3 = BitVector32.CreateMask(mask2);
int mask4 = BitVector32.CreateMask(mask3);

myBitVector[mask1] = false;
myBitVector[mask2] = true;
myBitVector[mask3] = true;
myBitVector[mask4] = false;

For complete details about the BitVector32 structure, click here!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: