Monday, May 16, 2011

BitArray in .NET

It’s been quite a while since the last time I published a post related to .NET programming and in this while my focus was on more fundamental aspects of programming languages and compilers reformatting my mind about some delicate details of languages and programming, but hopefully, I’m going to write more about .NET in the near future.

There are a set of classes and APIs in the .NET Framework that are used less by ordinary software developers engaged in commercial programming. This is in part due to the fact that such classes are designed with specific intentions by the framework designers, and that they are provided as some ways for writing more efficient code but commercial developers care less about this thank to the good performance of .NET Framework JIT compiler and advancements in hardware.
However, there are many cases where you really need to care about efficiency and write a clean code to accomplish something. A place where this may be happening is in hardware-related programs where you want to avoid any extra overhead on low-level manipulations of hardware interfaces.
Dealing with bits and small integers is one scenario where you may need to have to care more about efficiency. Although you’re probably dealing with small numbers, you’re actually dealing with the bits for each number that matter in size. The .NET Framework has provided some tools to facilitate programming for bits and working with them. One of these classes, that is actually a collection class, is System.Collections.BitArray.

BitArray class is a compact array of bit values that are represented as Boolean values (true corresponding to 1 and false corresponding to zero). This collection type can be used to store a collection of numbers as their bit values and apply bitwise operators to them in a fast, easy, and efficient manner. One good example of a scenario where such a class can be handy is in implementing programs like the one-level CPU cache simulator that I had implemented in ANSI C because such programs have an intense use of bitwise operators on the bits representing integer numbers. If you read my code and try to imagine writing such a program with C# and its regular types, you can understand how important it is to have specific classes developed for such purposes.

Read more: Keyvan Nayyeri