Thứ Sáu, 5 tháng 10, 2012

Convert Int32 to Base 2, 8, 10 or 16

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. Anyway, I converted the method I wrote to an extension method on Int32 called "InBase" - I think that reads better than Convert.ToString with a base passed in. The implementation is below in case you want to include it in your libraries.


public static string InBase(this int number, int @base)
{
    return Convert.ToString(number, @base);
}
Example usage:

Console.WriteLine("{0}", 10.InBase(2)); // Outputs "1010" (Binary)
Console.WriteLine("{0}", 10.InBase(8)); // Outputs "12" (Octal)
Console.WriteLine("{0}", 10.InBase(10)); // Outputs "10" (Decimal)
Console.WriteLine("{0}", 10.InBase(16)); // Outputs "a" (Hexadecimal)
Console.WriteLine("{0}", 10.InBase(3)); // Throws ArgumentException

Không có nhận xét nào:

Đăng nhận xét