Home
Map
BitVector32 ExampleUse the BitVector32 type from System.Collections.Specialized.
C#
This page was last reviewed on Sep 24, 2022.
BitVector32. This 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.
Detail 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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.