C# BitVector32 Example

This C# tutorial shows the BitVector32 type from System.Collections.Specialized.

BitVector32 provides bit-level abstractions.

It occupies 32 bits of memory. It provides methods that let you create masks and set and get bits. It is possible to use BitVector32 as an optimized group of 32 boolean values.

 

 

Example. This program first creates an array of masks. The BitVector32 type provides the CreateMask method for this purpose. It is possible to compute these masks in other ways. Each mask is simply an integer twice the value of the previous.

 

C# program that uses BitVector32

using System;
using System.Collections.Specialized;

class Program
{
    static int[] _masks; // Holds 32 masks.

    public static void Main()
    {
	// Initialize masks.
	_masks = new int[32];
	{
	    _masks[0] = BitVector32.CreateMask();
	}
	for (int i = 1; i < 32; i++)
	{
	    _masks[i] = BitVector32.CreateMask(_masks[i - 1]);
	}

	// Address single bits.
	BitVector32 v = new BitVector32();
	v[_masks[0]] = true;
	v[_masks[1]] = true;
	v[_masks[31]] = true;

	// Write bits.
	for (int i = 0; i < 32; i++)
	{
	    Console.Write(v[_masks[i]] == true ? 1 : 0);
	}
	Console.WriteLine();
    }
}

Output

11000000000000000000000000000001

The masks array is used to assign true or false to specific bits. Only 32 bits, indexed from 0 to 31, can be set or get. The for-loop prints out the values of the bits as 1 or 0. The first, second and last bits were set to true.

Tip: BitVector32 is an abstraction of readily available bitwise operators. You can use bitwise operators to duplicate the effects.

Also: This site has instructions on setting bits to zero. This requirement could be accomplished with BitVector32.

Set Bit to Zero

 

Performance. BitVector32 could improve performance in certain programs. It can replace a bool array. Every 32 booleans could be changed to one BitVector32. This means 32 booleans requiring 32 bytes of memory become one BitVector requiring 4 bytes.

 

C# program that compares bool and BitVector32

using System;
using System.Collections.Specialized;

class Program
{
    public static void Main()
    {
	{
	    Console.WriteLine(sizeof(bool));
	}
	unsafe
	{
	    Console.WriteLine(sizeof(BitVector32));
	}
    }
}

Output

1
4

 

Summary. BitVector32 provides important bitwise functionality. It is an abstract data type for bitwise operators upon on a 32-bit integer. It can reduce memory usage of certain programs. It does this at the cost of more confusing code.