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

后端 未结 12 1249
予麋鹿
予麋鹿 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条回答
  •  梦毁少年i
    2020-11-22 04:43

    I too was looking for a fast way to convert decimal number to another base in the range of [2..36] so I developed the following code. Its simple to follow and uses a Stringbuilder object as a proxy for a character buffer that we can index character by character. The code appears to be very fast compared to alternatives and a lot faster than initialising individual characters in a character array.

    For your own use you might prefer to: 1/ Return a blank string rather than throw an exception. 2/ remove the radix check to make the method run even faster 3/ Initialise the Stringbuilder object with 32 '0's and remove the the line result.Remove( 0, i );. This will cause the string to be returned with leading zeros and further increase the speed. 4/ Make the Stringbuilder object a static field within the class so no matter how many times the DecimalToBase method is called the Stringbuilder object is only initialised the once. If you do this change 3 above would no longer work.

    I hope someone finds this useful :)

    AtomicParadox

            static string DecimalToBase(int number, int radix)
        {
            // Check that the radix is between 2 and 36 inclusive
            if ( radix < 2 || radix > 36 )
                throw new ArgumentException("ConvertToBase(int number, int radix) - Radix must be between 2 and 36.");
    
            // Create a buffer large enough to hold the largest int value represented in binary digits 
            StringBuilder result = new StringBuilder("                                ");  // 32 spaces
    
            // The base conversion calculates the digits in reverse order so use
            // an index to point to the last unused space in our buffer
            int i = 32; 
    
            // Convert the number to the new base
            do
            {
                int remainder = number % radix;
                number = number / radix;
                if(remainder <= 9)
                    result[--i] = (char)(remainder + '0');  // Converts [0..9] to ASCII ['0'..'9']
                else
                    result[--i] = (char)(remainder + '7');  // Converts [10..36] to ASCII ['A'..'Z']
            } while ( number > 0 );
    
            // Remove the unwanted padding from the front of our buffer and return the result
            // Note i points to the last unused character in our buffer
            result.Remove( 0, i );
            return (result.ToString());
        }
    

提交回复
热议问题