Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB7
Expertise: Intermediate
Jul 6, 2002

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.Specialized

Dim bv As New BitVector32()
' set one element and read it back
bv(1) = True
Console.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 True
bv = 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 each
Dim 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 value
bv(se1) = 10
bv(se2) = 20
bv(se3) = 40
' read them back
Console.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 value
Console.WriteLine(bv.Data)                  ' => -11958
Console.WriteLine(bv.Data.ToString("X"))    ' => FFFFD14A
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap