【问题标题】:BigInteger Parse Octal String?BigInteger 解析八进制字符串?
【发布时间】:2012-12-12 00:07:51
【问题描述】:

在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 位,无符号)八进制值的方法。

【问题讨论】:

    标签: c# biginteger octal


    【解决方案1】:

    这可能不是最有效的解决方案,但如果性能不是优先考虑的因素,您可以手动构造BigInteger

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

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

    编辑:对于十六进制数字,您应该使用Parse 方法。如果您的号码应该被解释为正数,即使它的第一个字符是8F,请在前面加上0

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

    【讨论】:

    • 我不太确定发生了什么。是否有一种简单的方法来添加十六进制的实现? (解析大的十六进制字符串)
    • @BackpackOnHead 当你可以使用内置的 Parse 方法时,为什么要为十六进制添加一个实现?您不太可能改进 Microsoft 的实施。
    • @phoog - 我问了这个问题,然后我跳到床上,捂着脸,哈哈。
    【解决方案2】:

    一个简单的十六进制实现(所有基数不超过 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]);
    }
    

    【讨论】:

    • +1:这就是我将它扩展到大于 10 的非十六进制基数的方式。
    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2010-09-27
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多