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

后端 未结 12 1466
予麋鹿
予麋鹿 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:22

    This is a fairly straightforward way to do this, but it may not be the fastest. It is quite powerful because it is composable.

    public static IEnumerable ToBase(this int x, int b)
    {
        IEnumerable ToBaseReverse()
        {
            if (x == 0)
            {
                yield return 0;
                yield break;
            }
            int z = x;
            while (z > 0)
            {
                yield return z % b;
                z = z / b;
            }
        }
    
        return ToBaseReverse().Reverse();
    }
    

    Combine this with this simple extension method and any getting any base is now possible:

    public static string ToBase(this int number, string digits) =>
        String.Concat(number.ToBase(digits.Length).Select(x => digits[x]));
    

    It can be used like this:

    var result = 23.ToBase("01");
    var result2 = 23.ToBase("012X");
    
    Console.WriteLine(result);
    Console.WriteLine(result2);
    

    The output is:

    10111
    11X
    

提交回复
热议问题