Categories: development

Base36 Encoder/Decoder in C#

Edit: An updated Version (which also adds BigInteger compatibility) is part of my Utility Library on GitHub: https://github.com/mstum/mstum.utils

For a project I am working on I needed a way to convert long numbers into Base 36 numbers. Base 36 uses number 0 to 9 and letters a to z, but is not case sensitive (there is no differentiation between uppercase and lowercase letters), which makes it perfect for being transferred over the telephone.

As the .net Framework does not have a Built-In function for Base 36, I've converted the one from the Wikipedia Article to C#. Note that the "Reverse" function could as well be an extension Method if you use a more recent .net Framework, but to keep it simple it's an instance method here. You can test it against the examples in the Wikipedia article if you want to verify it.

By the way, I've chosen lowercase letters here, but if you want, you can just make them uppercase. Also, note that these functions work with a long, not with a double, so no floating point action here.

// Edit: Slightly updated on 2011-03-29

/// <summary>
/// A Base36 De- and Encoder
/// </summary>
public static class Base36
{
	private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";

	/// <summary>
	/// Encode the given number into a Base36 string
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	public static String Encode(long input)
	{
		if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");

		char[] clistarr = CharList.ToCharArray();
		var result = new Stack<char>();
		while (input != 0)
		{
			result.Push(clistarr[input % 36]);
			input /= 36;
		}
		return new string(result.ToArray());
	}

	/// <summary>
	/// Decode the Base36 Encoded string into a number
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	public static Int64 Decode(string input)
	{
		var reversed = input.ToLower().Reverse();
		long result = 0;
		int pos = 0;
		foreach (char c in reversed)
		{
			result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
			pos++;
		}
		return result;
	}
}