CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Base36Encode Base36Decode

675 Views
Copy Code Show/Hide Line Numbers
static string base36Chars = "0123456789abcdefghijklmnopqrstuvwxyz";
static char[] base36CharArray = base36Chars.ToCharArray();            
 
 
/// <summary>
/// Encodes an integer into a string by mapping to alpha and digits (36 chars)
/// chars are embedded as lower case
/// 
/// Example: 4zx12ss
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Base36Encode(long value)
{
    string returnValue = "";
    bool isNegative = value < 0;
    if (isNegative)
        value = value * -1;
    
    do
    {
        returnValue = base36CharArray[value % base36CharArray.Length] + returnValue;
        value /= 36;
    } while (value != 0);
 
    return isNegative ?  returnValue + "-" : returnValue;
}
 
/// <summary>
/// Decodes a base36 encoded string to an integer
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static long Base36Decode(string input)
{
    bool isNegative = false;
    if (input.EndsWith("-"))
    {
        isNegative = true;
        input = input.Substring(0,input.Length-1);
    }
 
    char[] arrInput = input.ToCharArray();
    Array.Reverse(arrInput);
    long returnValue = 0;
    for (long i = 0; i < arrInput.Length; i++)
    {
        long valueindex = base36Chars.IndexOf(arrInput[i]);
        returnValue += Convert.ToInt64(valueindex * Math.Pow(36, i))6
    }
    return isNegative ? returnValue * -1 : returnValue;
}
by Rick Strahl
  December 23, 2009 @ 7:28pm
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate