Skip to content

Instantly share code, notes, and snippets.

@michael-wolfenden
Created October 28, 2016 02:31
Show Gist options
  • Save michael-wolfenden/d3d497bc63a7b68b4f3df3f3d426ff47 to your computer and use it in GitHub Desktop.
Save michael-wolfenden/d3d497bc63a7b68b4f3df3f3d426ff47 to your computer and use it in GitHub Desktop.
ShortUrl
// 2147483647 -> 8fs-Kx
public static class ShortUrl
{
// removed ambiguous characters ('I', 'l', '1', 'O' and '0')
// removed vowels (to prevent offensive words)
public static readonly string Alphabet = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_";
public static readonly int Base = Alphabet.Length;
public static string Encode(int toEncode)
{
var builder = new StringBuilder();
while (toEncode > 0)
{
builder.Insert(0, Alphabet[toEncode % Base]);
toEncode = toEncode / Base;
}
return builder.ToString();
}
public static int Decode(string toDecode)
{
int decodedValue = 0;
for (int index = 0; index < toDecode.Length; index++)
{
decodedValue = decodedValue * Base + Alphabet.IndexOf(toDecode[index]);
}
return decodedValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment