7

在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提供了上面显示的格式化功能,但我似乎找不到解析 BIIIG(大于 64 位,无符号)八进制值的方法。

4

2 回答 2

13

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

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

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

编辑:对于十六进制数字,您应该使用该Parse方法。0如果您的数字应该被解释为正数,即使它的第一个字符是8–<code>F,也要加上前缀。

string s = "0F20051C5E45F4FD68F8E58905A133BCA";
BigInteger bi = BigInteger.Parse(s, NumberStyles.HexNumber);
于 2012-12-26T12:58:25.250 回答
3

十六进制的简单实现(所有基数最多为 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]);
}
于 2012-12-26T14:19:47.480 回答