Skip to content

Instantly share code, notes, and snippets.

@ruslander
Created January 25, 2013 02:39
Show Gist options
  • Save ruslander/4631288 to your computer and use it in GitHub Desktop.
Save ruslander/4631288 to your computer and use it in GitHub Desktop.
[Test]
public void decodeTest() {
Assert.AreEqual(19158, decode("e9a"));
}
[Test]
public void encodeTest()
{
Assert.AreEqual("cb", encode(125));
}
private String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private int BASE = 62;
public string encode(int num)
{
StringBuilder sb = new StringBuilder();
while ( num > 0 )
{
sb.Append( ALPHABET[num % BASE]);
num /= BASE;
}
var items = sb.ToString().ToCharArray();
Array.Reverse(items);
return new string(items);
}
public int decode(string str)
{
int num = 0;
for ( int i = 0, len = str.Length; i < len; i++ )
{
num = num * BASE + ALPHABET.IndexOf(str[i]);
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment