I had to implement going from string to decimal and back again. Thanks to @Pudge601 for the base 62 idea. Please find below a C# solution.
Limitations: Using long
data type, appears to only handle 10 characters or less at base 62. Using int32
, appears to only handle 5 characters at worst case - so it doesn't handle your example 'af45TR'
string.
readonly char[] charArray = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
void Main()
{
var stringToConvert = "HelloWorld";
var decimalVal = StringToDecimal(stringToConvert, 62); // outputs 598985658527080986
var result = DecimalToString(decimalVal, 62, stringToConvert.Length);
Console.WriteLine(result); // outputs HelloWorld
}
public string DecimalToString(long decimalInput, int desiredBased, int expectedStringLength)
{
Console.WriteLine($"Converting decimal value {decimalInput} to string using base {desiredBased}");
var index = 0; // Initialize index of result
var output = new char[expectedStringLength];
while (decimalInput > 0)
{
var deciValue = (decimalInput % desiredBased);
if (deciValue == 0) // handle Z value
deciValue = 62;
output[index] = charArray[deciValue-1];
index ++;
decimalInput = (decimalInput - deciValue) / desiredBased;
}
// Reverse the result
Array.Reverse(output);
return new string(output);
}
public long StringToDecimal(string input, int desiredBase)
{
Console.WriteLine($"Converting string value {input} to decimal using base {desiredBase}");
int len = input.Length;
long power = 1;
long num = 0;
for (var i = len - 1; i >= 0; i--)
{
if (Array.IndexOf(charArray, input[i]) + 1 > desiredBase)
{
throw new ArgumentException("Invalid base", nameof(desiredBase));
}
num += (Array.IndexOf(charArray, input[i]) + 1) * power;
power = power * desiredBase;
}
return num;
}
With help from geeksforgeeks, although their solution did not work straight out of the box for me.