public static Int64 Decode(string input)
{
var reversed = input.ToLower().Reverse();
long result = 0;
int pos = 0;
foreach (char c in reversed)
{
result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
pos++;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用一种方法将base36中的值解码为十进制.该方法工作正常,但当我解码输入值"000A"时,事情开始出错,并将其解码为-1.
任何人都可以看到出了什么问题?我真的很困惑代码及其工作原理.
private const string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Run Code Online (Sandbox Code Playgroud)
我只能假设你CharList不包含A,因此IndexOf(c)返回-1显示找不到该字符.请记住,IndexOf默认情况下区分大小写,因此如果您使用大写字母CharList和小写字母c,则它将不匹配.
// pos = 0
result += CharList.IndexOf(c) * (long)Math.Pow(36, pos);
// pos = 36^0 = 1
// CharList.IndexOf(c) gives -1 when not found
// therefore, it equates to:
result += -1 * 1
Run Code Online (Sandbox Code Playgroud)