Home
C#
BitArray Examples
This page was last reviewed on May 24, 2023.
Dot Net Perls
BitArray. This type offers C# programs a clear approach to bitwise operations. It allows us to perform bitwise operations. With it we count and display bits.
Along with BitConverter, BitArray allows us to use byte data in an efficient way. We can reduce memory usage, and avoid trying to remember bitwise operations.
BitConverter
First example. BitArray has many constructors—for int32, int32 arrays, byte arrays. When we pass values to the constructor, integers are copied, but bytes and bools are processed first.
Next We use the BitArray type. This example initializes a BitArray from a bool array.
Here The program creates a bool array with true and false values, and then the BitArray constructor converts those into one bit each.
bool Array
Info This means that instead of one byte for a bool, the values are stored as one bit, in one-eighth the space.
true, false
using System; using System.Collections; // Create array of 5 elements and 3 true values. bool[] array = new bool[5]; array[0] = true; array[1] = false; array[2] = true; array[3] = false; array[4] = true; // Create BitArray from the array. BitArray bitArray = new BitArray(array); // Display all bits. foreach (bool bit in bitArray) { Console.WriteLine(bit); }
True False True False True
Internals. BitArray contains an integer array that stores the bits themselves, and a separate length value. The length member is accessed through the Count property.
Info The Get method returns bit values by using an "AND" and shift on the internal array.
And Internally, each call to Get will result in the method checking all the parameters.
Tip This introduces two extra branches, which may be a burden on certain algorithms that require top performance.
Info I instrumented an application with CLRProfiler. This revealed that each bit in a BitArray is stored as a single bit in memory.
private int[] m_array; private int m_length;
Set, count. We assign bits with the indexer and the Set method, and also Count the BitArray's capacity. The program here also shows how to count bits set to one in a loop.
Info The Count on BitArray instances does not return the number of set bits. Instead, it returns the count of all bits of any value.
Bitcount
Tip You will need to loop over bits individually to count them. You can also use a for-loop.
using System; using System.Collections; class Program { static void Main() { // Create BitArray from the array. BitArray bitArray = new BitArray(32); // Set three bits to 1. bitArray[3] = true; // You can set the bits with the indexer. bitArray[5] = true; bitArray.Set(10, true); // You can set the bits with Set. // Count returns the total of all bits (1s and 0s). Console.WriteLine("--- Total bits ---"); Console.WriteLine(bitArray.Count); // You can loop to count set bits. Console.WriteLine("--- Total bits set to 1 ---"); Console.WriteLine(CountBitArray(bitArray)); } /// <summary> /// Count set bits in BitArray. /// </summary> static int CountBitArray(BitArray bitArray) { int count = 0; foreach (bool bit in bitArray) { if (bit) { count++; } } return count; } }
--- Total bits --- 32 --- Total bits set to 1 --- 3
Display. Here we display all the bits as ones and zeros in a BitArray. We also use the bitwise And method on BitArray, which shows how to get all the bits that are one in both arrays.
using System; using System.Collections; class Program { static void Main() { // // Initialize BitArray with 4 true bits and 12 false bits. // BitArray bitArray1 = new BitArray(16); bitArray1.Set(0, true); bitArray1.Set(1, true); bitArray1.Set(4, true); bitArray1.Set(5, true); // // Display the BitArray. // DisplayBitArray(bitArray1); // // Initialize BitArray with two set bits. // BitArray bitArray2 = new BitArray(16); bitArray2.Set(0, true); bitArray2.Set(7, true); DisplayBitArray(bitArray2); // // And the bits. // bitArray1.And(bitArray2); DisplayBitArray(bitArray1); } /// <summary> /// Display bits as 0s and 1s. /// </summary> static void DisplayBitArray(BitArray bitArray) { for (int i = 0; i < bitArray.Count; i++) { bool bit = bitArray.Get(i); Console.Write(bit ? 1 : 0); } Console.WriteLine(); } }
1100110000000000 1000000100000000 1000000000000000
Performance, BitArray. How does the performance of BitArray in C# compare to a bool array? BitArray is more compact in memory, but this may come at some runtime cost.
Version 1 This version of the code tests an element in the bool array that was allocated and populated in the setup section.
Version 2 Here we use the BitArray we created. We access it in the same way as the bool array, and the end "count" values are the same.
Result The bool array is faster than BitArray in this benchmark. This was tested in .NET 5 for Linux (2021).
using System; using System.Collections; using System.Diagnostics; const int _max = 100000000; // Set up. const int itemsMax = 100000; var array = new bool[_max]; // Store bool in each array index. for (int i = 0; i < array.Length; i++) { array[i] = i % 2 == 0; } // Create BitArray. var bits = new BitArray(array); int count = 0; int count2 = 0; var s1 = Stopwatch.StartNew(); // Version 1: lookup element in bool array. for (int i = 0; i < _max; i++) { if (array[i % itemsMax] == true) { count++; } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use BitArray. for (int i = 0; i < _max; i++) { if (bits[i % itemsMax] == true) { count2++; } } s2.Stop(); Console.WriteLine(count + "==" + count2); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
50000000==50000000 1.55 ns bool[] 2.15 ns BitArray
Bitwise methods. The BitArray class defines several more useful methods you can call. Not(), Or() and Xor() provide functionality equivalent to the bitwise operators.
BitArray is a powerful wrapper over the complex bitwise operations that connect an array of four-byte integers with single bits. It is memory-efficient and easy to reuse.
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 May 24, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.