Skip to content

Instantly share code, notes, and snippets.

@shibayan
Last active October 9, 2015 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shibayan/3507102 to your computer and use it in GitHub Desktop.
Save shibayan/3507102 to your computer and use it in GitHub Desktop.
public class RadixConvert
{
private const int Radix = 62;
private const string Table = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static string Encode(long number)
{
const int length = 16;
int index = length;
var buffer = new char[length];
do
{
buffer[--index] = Table[(int)(number % Radix)];
number = number / Radix;
} while (number != 0);
return new string(buffer, index, length - index);
}
public static long Decode(string str)
{
long pow = 1;
long result = 0;
for (int i = str.Length - 1; i >= 0; i--)
{
int digit;
if ((byte)(str[i] - '0') < 10)
{
digit = str[i] - '0';
}
else if ((byte)(str[i] - 'a') < 26)
{
digit = str[i] - 'a' + 10;
}
else if ((byte)(str[i] - 'A') < 26)
{
digit = str[i] - 'A' + 36;
}
else
{
return -1;
}
result = result + (digit * pow);
pow = pow * Radix;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment