BigInteger Parse Octal String?

后端 未结 2 559
无人及你
无人及你 2020-12-06 13:06

In Java, I could do

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

Then f

2条回答
  •  抹茶落季
    2020-12-06 13:40

    A simple implementation for hex (and all bases up to 16); expand it by adding characters to the string constant (credit where credit is due; this is based on Douglas's answer):

    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]);
    }
    

    It is likely that arithmetic where one operand is an int is faster than if both operands are BigInteger. In that case:

    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]);
    }
    

提交回复
热议问题