Quickest way to convert a base 10 number to any base in .NET?

后端 未结 12 1388
予麋鹿
予麋鹿 2020-11-22 04:07

I have and old(ish) C# method I wrote that takes a number and converts it to any base:

string ConvertToBase(int number, char[] baseChars);

12条回答
  •  执笔经年
    2020-11-22 04:19

    I recently blogged about this. My implementation does not use any string operations during the calculations, which makes it very fast. Conversion to any numeral system with base from 2 to 36 is supported:

    /// 
    /// Converts the given decimal number to the numeral system with the
    /// specified radix (in the range [2, 36]).
    /// 
    /// The number to convert.
    /// The radix of the destination numeral system (in the range [2, 36]).
    /// 
    public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
    {
        const int BitsInLong = 64;
        const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
        if (radix < 2 || radix > Digits.Length)
            throw new ArgumentException("The radix must be >= 2 and <= " + Digits.Length.ToString());
    
        if (decimalNumber == 0)
            return "0";
    
        int index = BitsInLong - 1;
        long currentNumber = Math.Abs(decimalNumber);
        char[] charArray = new char[BitsInLong];
    
        while (currentNumber != 0)
        {
            int remainder = (int)(currentNumber % radix);
            charArray[index--] = Digits[remainder];
            currentNumber = currentNumber / radix;
        }
    
        string result = new String(charArray, index + 1, BitsInLong - index - 1);
        if (decimalNumber < 0)
        {
            result = "-" + result;
        }
    
        return result;
    }
    

    I've also implemented a fast inverse function in case anyone needs it too: Arbitrary to Decimal Numeral System.

提交回复
热议问题