Take advantage of the BitArray class in .NET 7 to perform bitwise operations on your data for improved performance. Credit: Suebsiri / Getty Images The BitArray class in .NET 7 is a robust data structure that stores and manipulates bits of data. Each element in a BitArray can only hold a single bit (0 or 1) represented as false or true, where false indicates the bit is off (0) and true indicates the bit is on (1). BitArrays can store flags or efficiently perform bitwise operations on data. This article talks about using BitArray in C# with relevant code examples wherever applicable. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here. Create a console application project in Visual Studio First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. Click Next In the “Additional information” window shown next, choose “.NET 7 (Preview)” as the Framework version you would like to use. Click Create. We’ll use this .NET 7 console application project to work with BitArray in the subsequent sections of this article. What is a BitArray? A BitArray is a type contained in the System.Collections namespace that represents a compact array of bit values. These values are expressed as boolean values, i.e., true and false. Here, the value true means the bit is on, and the value false means the bit is off. Because the BitArray class is located in the System.Collections namespace, you will need to include a using directive for that namespace in your code. The BitArray class is declared in the System.Collections namespace as shown below. public sealed class BitArray : ICloneable, System.Collections.ICollection Create a BitArray in .NET 7 You can create a BitArray of a certain size and fill it with all false values as shown in the code snippet given below. var bitArray = new BitArray(10); You can also pass in a list of booleans to create a BitArray of a specific size and set the values. var bitArray = new BitArray(new bool[] {true, false, true}); Once you have created your BitArray, you can access and manipulate the individual bits using the indexer. The indexer expects an integer and will return or set the value of that bit. bitArray[0] = true //sets the first bit to true bitArray[1] = false //sets the second bit to false bitArray[0] //returns the value of the first bit (as a bool) The following code snippet can be used to create a BitArray, set values to its elements, and then retrieve and display the value of a particular index in the BitArray. BitArray bitArray = new BitArray(5); bitArray[0] = true; bitArray[1] = false; bitArray[2] = true; bitArray[3] = false; bitArray[4] = false; Console.WriteLine(bitArray.Get(2)); Console.WriteLine(bitArray.Get(4)); When you execute the above piece of code, the values true and false will be displayed at the console window as shown in Figure 1. IDG Figure 1. Manipulate bits in a BitArray You can manipulate the bits in a BitArray either using its index or using the Get and Set methods of the BitArray class. To set or retrieve multiple bits from a BitArray, you can use the SetAll() and GetAll() methods as shown in the code snippet given below. bitArray.SetAll(false); //set all bits of the bit array to 0 bitArray.Set(0, true); //set first bit of the bit array to 1 bitArray.Set(1, false); //set the second bit of the bit array to 0 bool result = (bitArray[0] == 1); //verify if first bit is equal to 1 Check if a BitArray is read-only If you need to check if a BitArray is ReadOnly, you can use the IsReadOnly property. This property returns a Boolean value that indicates whether the BitArray is read-only. The following code snippet shows how you can check if a BitArray is read-only. BitArray bitArray = new BitArray(new byte[] { 0, 1, 0, 1, 0 }); Console.WriteLine(bitArray.IsReadOnly); When you execute the above piece of code, the text “False” will be displayed at the console window. Length and Count properties in a BitArray The Length property of a BitArray returns the number of bits in the array. The Count property returns the count of the number of true and false values in the BitArray. Note that the Length property will always return the total number of bits in the array, even if all of them are false. In other words, the Length and Count properties will display identical values for a BitArray. The following piece of code illustrates how you can get the Length and Count of a BitArray. var bitArray = new BitArray(new bool[] { true, false, true, false }); Console.WriteLine("Length: " + bitArray.Length); Console.WriteLine("Count: " + bitArray.Count); When you execute the above code, the output will be similar to that shown in Figure 2. IDG Figure 2. You may want to check whether or not your BitArray instance is synchronized. This can be done by calling the instance’s IsSynchronized property, which will return true if the BitArray is synchronized and false otherwise. Perform AND, OR, and NOT operations in a BitArray The following code listing shows how you can perform a bitwise AND operation on two BitArray instances. A bitwise AND operation returns true (or 1) if both operands are true, and returns false otherwise. A bitwise OR operation returns true if either or both operands are true, and false otherwise. var bitArray1 = new BitArray(new bool[] { true, false, true, false, true }); var bitArray2 = new BitArray(new bool[] { true, false, true, true, true }); bitArray1.Set(0, true); bitArray1.Set(1, false); bitArray1.Set(2, true); bitArray1.Set(3, true); bitArray1.Set(4, false); bitArray2.Set(0, true); bitArray2.Set(1, true); bitArray2.Set(2, false); bitArray2.Set(3, true); bitArray2.Set(4, false); bitArray1.And(bitArray2); Console.WriteLine("Displaying the elements of bitArray1 after AND operation"); for (int i = 0; i < bitArray1.Count; i++) { Console.Write(bitArray1[i] + "t"); } When you execute the above code, the value of each element of bitArray1 will be displayed after the AND operation. IDG Figure 3. To perform a bitwise OR operation on two BitArrays, you can simply replace the AND operator with the OR operator in the preceding example. In other words, replace bitArray1.And(bitArray2) with bitArray1.Or(bitArray2). var bitArray1 = new BitArray(new bool[] { true, false, true, false, true }); var bitArray2 = new BitArray(new bool[] { true, false, true, true, true }); bitArray1.Set(0, true); bitArray1.Set(1, false); bitArray1.Set(2, true); bitArray1.Set(3, true); bitArray1.Set(4, false); bitArray2.Set(0, true); bitArray2.Set(1, true); bitArray2.Set(2, false); bitArray2.Set(3, true); bitArray2.Set(4, false); bitArray1.Or(bitArray2); Console.WriteLine("Displaying the elements of bitArray1 after OR operation"); for (int i = 0; i < bitArray1.Count; i++) { Console.Write(bitArray1[i] + "t"); } Performing a NOT operation on a BitArray will change all true elements to false and vice versa. The following code snippet would change the elements of bitArray1 from { true, false, false, true, false } to { false, true, true, false, true }. bitArray1.Not(); Common uses for BitArrays There are a number of common use cases for a BitArray, such as for performing bitwise operations to manipulate an image. The color of each pixel in an image is defined by a certain number of bits. Changing the color of a pixel requires manipulating the bits that comprise it. Using BitArray, it is easy to manipulate individual bits within an array. BitArray is also commonly used when dealing with network packets. Packets contain a large amount of data, which may be formatted as bits or bytes depending on the protocol. You can easily extract and manipulate the bits contained in each packet with BitArray. You can also use a BitArray to represent Boolean values in your application. By doing so, you can reduce your memory and storage requirements. A BitArray consumes 1/8th the space consumed by a bool because a BitArray stores only one bit for each value. Additionally, whereas a byte can hold only eight values and an integer can hold only 32, a BitArray can hold an arbitrary number of boolean values. If you are storing a massive amount of data, this difference can be quite significant. Finally, when it comes to processing a huge collection, the advantages of BitArray and bitwise processing will become clear as soon as you start fetching data from the memory. For example, there will be a significant difference in performance between a BitArray of 10000 items and a List of 10000 items. There will be eight times more memory reads required for the List than for the BitArray. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos