Thursday 12 August 2010

Converting Base10 to Base36

Here is a simple C# helper class for converting between base 10 and base 36.

public static class Base36Helper
{
    private const string Alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";

    public static string Encode(int value)
    {
        if (value < Alphabet.Length)
        {
            return Alphabet[value].ToString();
        }

        var result = new StringBuilder();

        while (value != 0)
        {
            result.Insert(0, Alphabet[value % 36]);
            value /= 36;
        }

        return result.ToString();
    }

    public static int Decode(string value)
    {
        int result = 0;

        for (int i = 0, j = (value.Length - 1); i < value.Length; i++, j--)
        {
            result += Alphabet.IndexOf(value[j]) * (int)Math.Pow(36, i);
        }

        return result;
    }
}

No comments:

Post a Comment