Skip to content

Instantly share code, notes, and snippets.

@danielrozo
Created July 21, 2013 12:27
Show Gist options
  • Save danielrozo/6048412 to your computer and use it in GitHub Desktop.
Save danielrozo/6048412 to your computer and use it in GitHub Desktop.
Extension methods for long to convert from/to Base 62. Useful for shrinking long numbers to small strings for URLs (bit.ly like).
public static string ToBase62(this long input)
{
string baseChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string r = string.Empty;
int targetBase = baseChars.Length;
do
{
r = string.Format("{0}{1}",
baseChars[(int)(input % targetBase)],
r);
input /= targetBase;
} while (input > 0);
return r;
}
public static long FromBase62(this string input)
{
string baseChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int srcBase = baseChars.Length;
long id = 0;
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
string r = new string(charArray);
for (int i = 0; i < r.Length; i++)
{
int charIndex = baseChars.IndexOf(r[i]);
id += charIndex * (long)Math.Pow(srcBase, i);
}
return id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment