.NET Framework Gem of the Week

February 28, 2006
No Comments.

Url: http://msdn.microsoft.com/library/default.asp?u…

Every week (until I run out of Gems), I will post a new class or structure that I find in the .NET Framework that I never knew existed…and that I think rocks…

This week, the BitVector32 structure.

This little gem wraps a 32 bit integer to allow access to individual bits (instead of the BitArray or doing the binary math yourself, which is a bit cumbersome). It does this by allowing you to create bit masks (without having to understand the binary math) and to use the structure’s indexer to get at that mask.  For example:

int firstBit = BitVector32.CreateMask();int secondBit = BitVector32.CreateMask(firstBit);int thirdBit = BitVector32.CreateMask(secondBit);
BitVector vector = new BitVector(4);
bool isBit3 = vector[thirdBit];

or you can set it with the same syntax:

vector[secondBit] = true;

Nice, huh?  Where it really shines is in packing bits. Bit packing is taking several smaller numbers and packing them into one large number. This is often done to decrease storage of especially small numbers.

If we wanted to store two numbers, instead of doing the binary math to figure out how many bits we needed to use and doing the bit shifting, the BitVector32 does it for us.  Just create a section and specify the maximum number to store:

BitVector32.Section firstSection = BitVector32.CreateSection(25);BitVector32.Section secondSection = BitVector32.CreateSection(100, firstSection);

Then you can just get and set the section with the indexer as well:

BitVector32 packedBits = new BitVector32(0);
packedBits[firstSection] = 10;packedBits[secondSection] = 50;

Underneath it all is the 32 bit integer that you can always access to get the resulting number in your result:


One other nice feature is if you do ToString() on the structure, it shows you the number as binary to help debug bit issues you might have.

Console.WriteLine(packedBits);// BitVector32{00000000000000011000000000001010}