Thursday, July 16, 2009

A c# class to convert between bases

Ever needed to work with numbers in base 17, or base 3? I have always wanted to write a Genetic algorithm that used base 3 numbers to represent the board - 0 empty, 1 my piece, 2 opponent piece. Recently at work, we needed to work with base 36 numbers. While doing some searching I also learned that some people needed numbers that were alpha-int (Where the letters preceded the numbers) instead of the standard int-alpha.

Here is a class that I think Microsoft left out. We work different systems and different numbers every day, so why didn't Microsoft include a base converter class? It probably was just too low on their list of priorities.

Well, here is my interpretation. It is a static class that exposes three overloaded functions:
Encode(long Value, sbyte Base)
Encode(long Value, sbyte Base, bool NumeralsFirst)
Decode(string Input, sbyte Base)
Decode(string Input, sbyte Base, bool NumeralsFirst)
BetweenBases(string Value, sbyte FromBase, sbyte ToBase)
BetweenBases(string Value, sbyte FromBase, sbyte ToBase, bool NumeralsFirst)

By using the BetweenBases function, you can convert directly from one base to another without decoding to a long in between.

The complete code for the class can be downloaded here.