Low level operations are commonplace for embedded developers but usually are overlooked by application level developers, but they still offer some useful quirks. After reading a few articles I decided to port some of the most common and useful bit level hacks to C#.

More information about the built in operators that are found in C# can be found on MSDN and the basis of this article can be found here along with additional info on how each of the bit level operations were performed.

Checking whether an integer is even

One of the most common and easy to understand operations is checking whether a value is even or odd. This is done by checking whether the least significant bit is 1 (odd) or 0 (even). This is done by AND-ing the value with 1 (00000001). The result will be 0 if even or 1 for odd.

As we are AND-ing with 1 (00000001) only a comparison is made on the least significant bit, thus this method works whatever value the input number is.

Some applications use an integer as a set of bit flags, C# does provide some limited functionality for this but here is an easy way to check whether a bit at a specific index is set.

Whether this and following methods ask for an index parameter, I check whether it is in range. I use the sizeof() function on the int as it could be different depending on whether you are working on a 32 or 64bit system.

This uses the shift operator << to move 1 bit back a specific number of places and then using the previous IsEven trick to determine whether the bit is set.

Set a Bit
Carrying on with the concept of using bit flags, this method sets a bit to 1 at a specific index in the bit array representing the integer.

Instead of performing a check, we use the OR operator | to set the value. This works because using the OR operator, the bit value will always be set, regardless of the original bit value. e.g. 0 OR 1 = 1, 1 OR 1 = 1

5 Responses to Bit level functionality in C#

Using the FlagsAttribute (http://msdn.microsoft.com/en-us/library/system.flagsattribute(v=vs.100).aspx) does allow bitwise operators but it has a few drawbacks; when handling large enums (if you want to make a 64 element enum be my guest) and more importantly if the data is being processed dynamically. Using an enumeration is good if the data is predefined and thus the enum elements can match up with the input data, but Microsoft says it is a no no to future proof enums with dummy values.

Your email address will not be published. Required fields are marked *

Search

Search for:

Software Engineer. Tea Drinker.

To those that say you can not change the world with source code, I say you are not trying hard enough.

My name is Kevin Pfister, I am currently employed as a Software Engineer specializing in Embedded Solutions after finishing my Software Engineering degree at York. I was an Academic Developer Evanglist at Microsoft, World renowned author and a world-wide finalist in the Imagine Cup developer competition in both 2010 and 2011