Store bits and small integers efficiently in a BitVector32

The System.Collections.Specialized.BitVector32 structure can be used to store up to 32 boolean values, or a set of small integers that can take up to 32 consecutive bits. The BitVector32 is similar to the BitArray class, in that it can hold boolean values that take only one bit each, yet it is more efficient because it is a structure instead of a class.

The simplest way to use a BitVector32 structure is to hold up to 32 boolean values:

' This code assume that you have the following Imports'    Imports System.Collections.SpecializedDim bv As New BitVector32()' set one element and read it backbv(1) = TrueConsole.WriteLine(bv(1))    ' => True

You can also pass a 32-bit integer to the constructor to initialize all the elements in one pass. For example:

'initialize all elements to Truebv = new BitVector32(-1)

To define a BitVector32 that is subdivided in sections that are longer than 1 bit you must create one or more BitVector32.Section objects, and use them when you later read and write individual elements. You define a section by means of the BitVector32.CreateSection shared method, that takes the highest integer you want to store in that section and (for all sections after the 1st one) the previous section. Here’s a complete example:

Dim bv As New BitVector32()' create three sections, of 4, 5, and 6 bits eachDim se1 As BitVector32.Section = BitVector32.CreateSection(15)Dim se2 As BitVector32.Section = BitVector32.CreateSection(31, se1)Dim se3 As BitVector32.Section = BitVector32.CreateSection(63, se2)' set each section at a given valuebv(se1) = 10bv(se2) = 20bv(se3) = 40' read them backConsole.WriteLine(bv(se1))Console.WriteLine(bv(se2))Console.WriteLine(bv(se3))

The Data property sets or returns the internal 32-bit value; you can use this property to save the value into a database field:

' continuing the previous code sample' read the entire field as a 32-bit valueConsole.WriteLine(bv.Data)                  ' => -11958Console.WriteLine(bv.Data.ToString("X"))    ' => FFFFD14A

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: