Created
January 25, 2013 02:39
-
-
Save ruslander/4631288 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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