One of my favorite assignments from University was implementing a compression utility using Huffman coding in ML. My nostalgic recollections of those times spurred the curious thought of re-developing this utility in C# to see how I've progressed as a developer in the 4 years since my graduation.
During my re-development of this utility, leveraging C#'s bitwise operators was unavoidable. This was mostly due to the fact that I wanted to avoid using a BitArray and rather concern myself with packing and shifting unsigned integers.
For those of you unfamiliar with the bitwise operators provided by C#, here is a quick run-down:
- & - bitwise AND
- | - bitwise OR
- ^ - bitwise XOR (works double duty as a logical XOR on boolean types)
- ~ - bitwise complement
- << - left bit shift
- >> - right bit shift
Somewhere along the way, I had the need for a BitSet function. That is, a function which would toggle a single bit at a certain index in some bit string on and off. C# does not provide an operator or function for this type of operation, but that's OK since it is trivial to implement using some of the bitwise operators from above:
static int SetBit(int i, int index, bool on)
{
//if (index > (sizeof(int) * 8 - 1))
//{
// throw new ArgumentException("Index out of bit range.");
//}
if (on)
{
return i | (1 << index);
}
else
{
return i & ~(1 << index);
}
}
I won't go into the details since the people reading this will fall into one of two camps. The first being those who know what this does by reading it, and the second being those who don't understand bitwise operations enough to know what this does. The latter will benefit from my lack of explanation if they examine the effects of the SetBit function on some bit patterns of their choosing.
You may be curious why I'm not bounds checking the value of the "index" argument (the comments in green). First, I didn't need to in the context of my compression utility. Second, the shift operators will gladly shift n bits in a bit string of length m where n > m without resulting in an exception. Go ahead and try it. Of course this situation may be an error in the context of your program. If so, utilize the commented code.
In the spirit of theory from my past, I'm off to prepare a blog post on streams. Check back soon, It won't be as long as the break was between my previous post and this one.