Bitwise kata

In April I embarked on what I hoped would be a regular practice of making small improvements to my coding knowledge and skills. One of the gaps I identified was a very poor understanding of a fundamental concept in computer science: bits and bytes and how to work with them. This week I did some work to make that gap a bit smaller.

The last exercise I did used a bitvector to sort a whole lot of numbers quickly. I had taken some code I found on GitHub to do the actual getting and setting of bits in the bit vector. I knew what it was doing in theory, but the actual practical code was a mystery to me. What were these >> and << operators. How did the actual 1 or 0 get set?

I broke it into two exercises. In the first exercise I worked through some examples from the Wikipedia page on bitwise operations on paper and wrote  program to test if I got it right.  I wrote it in C, again, and used assertions to tell me of my working was correct. While I was there, I found out a bit more about IO in C, too.

Doing it on paper was great. It completely demystified the process. It’s just about moving ones and zeros around, turning them off or on with neat, understandable tricks.

The second exercise was to document my sorting program to explain what was happening in the set_bit() function. Comments as documentation is a smell in production code but it’s entirely appropriate for this kind of exercise.

Reader, I’m not ashamed to admit that prior to the last couple of weeks the thought of digging into code that used pointers and manipulated the basic atoms of data was, well, scary. Now it’s not. It’s fun. I’m going to keep using C for the rest of the Programming Pearls exercises.