我有一串数字,我想缩短它们以便在 URL 中使用。该字符串始终只包含数字。例如:9587661771112
理论上,将数字字符串加密为字母数字(0-9a-zA-Z)字符串应该总是返回较短的结果,这正是我想要的。
我创建了一个执行以下操作的算法:
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
在下一步中,数字将是 58 等等。
通过一些调整,我能得到的最短结果是:9587661771112 > j9UQpjva
我的问题是,使用这种技术,结果可能会有很大差异。我也觉得这不是我的问题的干净解决方案。
所以我需要一种加密算法,将一串数字转换成较短的大写字母、小写字母和数字串。它必须是可解密的,并且具有或多或少一致的结果。
知道如何实现吗?
解决方法:
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;
}
就像一个魅力:)
最佳答案
解决方法:
string Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static string Base10To62(string S)
{
string R = "";
var N = long.Parse(S);
do { R += Chars[(int)(N % 0x3E)]; } while ((N /= 0x3E) != 0);
return R;
}
private static string Base62To10(string S)
{
long R = 0;
int L = S.Length;
for (int i = 0; i < L; i++) R += Chars.IndexOf(S[i]) * (long)(System.Math.Pow(0x3E, i));
return R.ToString();
}
关于c# - 将一串数字加密为一串字母数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11754675/