I have a string of numbers that i would like to make shorter for use in a URL. This string always consists of numbers only. For example: 9587661771112
In theory, encrypting a numeric string into an alphanumeric(0-9a-zA-Z) string should always return a shorter result, which is what i want.
I've created an algorithm that does the following:
Encrypt ( string1 = numeric input string, string2 = alphanumeric return string)
- Takes the next two characters from string1 and converts them into a number, e.g 95 for the above example
- Checks if the number is less than 52(the combined length of a-z and A-Z)
- if so, adds ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")[Number] to string2 and jump forward by 2 characters
- else, add ("0123456789)[First digit of Number) to string2 and jump forward by 1 character
In the next step the number would be 58 and so on.
With some tweaking the shortest result i could get was: 9587661771112 > j9UQpjva
My problem is that with this technique, the result can vary dramaticaly. I also feel that this is not a clean solution to my problem.
So I need an encryption algorithm that converts a string of numbers into a shorter string of uppercase letters, lowercase letters and numbers. It has to be decryptable and have a more or less consistent result.
Any idea how to achieve this?
Solution:
string Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string Base10To62(long N)
{
string R = "";
while (N != 0)
{
R += Chars[(int)(N % 62)];
N /= 62;
}
return R;
}
long Base62To10(string N)
{
long R = 0;
int L = N.Length;
for (int i = 0; i < L; i++)
{
R += Chars.IndexOf(N[i]) * (long)Math.Pow(62, i);
}
return R;
}
works like a charm :)