BitVector32
This .NET type 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. This type can result in confusing code.
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.
for
-loop prints out the values of the bits as 1 or 0. The first, second and last bits were set to true.BitVector32
is an abstraction of readily available bitwise operators. You can use bitwise operators to duplicate the effects.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(); } }11000000000000000000000000000001
BitVector32
could improve performance in certain programs. It can replace a bool
array. Every 32 booleans could be changed to one BitVector32
.
BitVector
requiring 4 bytes.using System; using System.Collections.Specialized; class Program { public static void Main() { { Console.WriteLine(sizeof(bool)); } unsafe { Console.WriteLine(sizeof(BitVector32)); } } }1 4
BitVector32
provides 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.