BigInteger解析八进制字符串?

在Java中,我能做到

//Parsing Octal String BigInteger b = new BigInteger("16304103460644701340432043410021040424210140423204",8); 

然后按我的喜好格式化它

 b.toString(2); //2 for binary b.toString(10); //10 for decimal b.toString(16); //16 for hexadecimal 

C#的BigInteger提供了上面显示的格式化function,但我似乎无法找到解析BIIIG(大于64位,无符号)八进制值的方法。

这可能不是最有效的解决方案,但如果性能不是优先级,您可以手动构建BigInteger

 string s = "16304103460644701340432043410021040424210140423204"; BigInteger bi = s.Aggregate(new BigInteger(), (b, c) => b * 8 + c - '0'); 

上述解决方案也适用于任何不大于10的基础; 只需将上述代码中的8替换为您所需的基数。

编辑 :对于hex数,您应该使用Parse方法。 如果您的数字应被解释为正数,则前缀为0 ,即使其第一个字符为8F

 string s = "0F20051C5E45F4FD68F8E58905A133BCA"; BigInteger bi = BigInteger.Parse(s, NumberStyles.HexNumber); 

hex的简单实现(以及最多16个的所有基数); 通过在字符串常量中添加字符来扩展它(信用到期的信用;这是基于Douglas的答案):

 private const string digits = "0123456789ABCDEF"; private readonly Dictionary 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 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]); }