十六进制的简单实现(所有基数最多为 16);通过向字符串常量添加字符来扩展它(信用到期的信用;这是基于道格拉斯的回答):
private const string digits = "0123456789ABCDEF";
private readonly Dictionary<char, BigInteger> values
= digits.ToDictionary(c => c, c => (BigInteger)digits.IndexOf(c));
public BigInteger ParseBigInteger(string value, BigInteger baseOfValue)
{
return value.Aggregate(
new BigInteger,
(current, digit) => current * baseOfValue + values[digit]);
}
一个操作数为 int 的算术运算可能比两个操作数均为 BigInteger 时更快。在这种情况下:
private readonly Dictionary<char, int> values
= digits.ToDictionary(c => c, c => digits.IndexOf(c));
public BigInteger ParseBigInteger(string value, int baseOfValue)
{
return value.Aggregate(
new BigInteger,
(current, digit) => current * baseOfValue + values[digit]);
}