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<int> ToBase(this int x, int b)
{
IEnumerable<int> 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