I'm new to C#.
I need a type with radix (or base) 3 (that is it counts 0 - 1 - 2 - 10 -
11 - 12 - 20 ...)
How do I construct that in C# ?
Types don't really have bases - a number is just a number, until it's
converted to a string form. What you *could* do is write a static
method to convert any integer to a string in base 3. It could be
something like this:
using System;
using System.Text;
public class Test
{
static void Main()
{
Console.WriteLine (IntToCustomBase(12, 3));
}
static string IntToCustomBase(int value, int toBase)
{
// Insert error checking for toBase being invalid here.
// This method can only cope with toBase being in the
// range 2-10.
if (value==0)
{
return "0";
}
bool negate = value < 0;
if (negate)
{
// Fix the '-' character later; deal
// with it as a positive number for now.
value = -value;
}
StringBuilder digits = new StringBuilder();
while (value > 0)
{
digits.Append ((char)('0'+(value%toBase)));
value = value/toBase;
}
if (negate)
{
digits.Append('-');
}
// Now we've got the string the wrong way
// round in the StringBuilder, so reverse it:
StringBuilder ret = new StringBuilder(digits.Length);
for (int i=digits.Length-1; i >= 0; i--)
{
ret.Append(digits
);
}
return ret.ToString();
}
}