Friday 5 October 2012

C# How To: Convert Integer to Base Binary, Octal, Denary or Hexadecimal

A few weeks ago I had a requirement to convert an Int32 value (base 10 or decimal) to its binary representation as a string. I encapsulated the logic to convert the decimal number to a binary string in a method. I used the base 10 to base 2 algorithm where the decimal number is continiously divided by two until it becomes zero. Within the iteration, the modulo two of the number is then appended to the output binary string. At the time of writing that code, it seemed like the best way to go about it, and because it was neatly encapsulated in a method, I knew I could swap out the implementation at a later date without much hassle.

Today, I came across an overload of the Convert.ToString method which surprisingly accepted a parameter called toBase. I wish I had come across this earlier... The overload accepts the bases 2, 8, 10 or 16 and throws an ArgumentException if one of these are not passed in. Examples are below:

Console.WriteLine("{0}", Convert.ToString(10,2));  // Outputs "1010
Console.WriteLine("{0}", Convert.ToString(10,8));  // Outputs "12"
Console.WriteLine("{0}", Convert.ToString(10,10)); // Outputs "10"
Console.WriteLine("{0}", Convert.ToString(10,16)); // Outputs "a"
Console.WriteLine("{0}", Convert.ToString(10,3));  // Throws ArgumentException

Thursday 4 October 2012

The Pragmatic Programmer

When studying for my undergrad degree, one of my lecturers recommended the book The Pragmatic Programmer (by Andrew Hunt and David Thomas). The book is written by a couple of experienced Software Engineers and contains a wealth of useful knowledge for anyone who is considering a serious career in software development.

The topics covered range from general tips that the authors learnt from their experiences, some useful tools you should know about as a programmer, how to think when you're writing code, how to write testable code and much more. It's a mixed bag of eight chapters, with each chapter broken down into smaller digestable sections. It was the perfect companion to someone who commuted into university on the train.

I know this post isn't relevant to C# per se, but thought it may encourage you to get hold of the book and learn some useful practices that you can apply in your projects.