Home
C#
BitVector32 Example
Updated Mar 17, 2025
Dot Net Perls
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.
Type notes. 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.
Info 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.
Result The for-loop prints out the values of the bits as 1 or 0. The first, second and last bits were set to true.
for
Tip BitVector32 is an abstraction of readily available bitwise operators. You can use bitwise operators to duplicate the effects.
Bitwise Set Bit
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
Performance. BitVector32 could improve performance in certain programs. It can replace a bool array. Every 32 booleans could be changed to one BitVector32.
Info This means 32 booleans requiring 32 bytes of memory become one 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 17, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen