Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToInt32 supports only 4 bases?

I'm trying to convert 12122 ( base 3) to int value ,

However I saw in reflector - the supported bases are 2,8,10,16

public static int ToInt32(string value, int fromBase)
{
    if (((fromBase != 2) && (fromBase != 8)) && ((fromBase != 10) && (fromBase != 0x10)))
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
    }
    return ParseNumbers.StringToInt(value, fromBase, 0x1000);
}

(I think they missed the 4 between 2-8 but nevermind.... )

So , how can I convert base 3 to base 10 ? ( Why didn't they give the option anyway?...)

like image 941
Royi Namir Avatar asked Jan 30 '26 20:01

Royi Namir


1 Answers

From this link

public static string IntToString(int value, char[] baseChars)
{
    string result = string.Empty;
    int targetBase = baseChars.Length;

    do
    {
        result = baseChars[value % targetBase] + result;
        value = value / targetBase;
    } 
    while (value > 0);

    return result;
}

Use like following

    string binary = IntToString(42, new char[] { '0', '1' });

    string base3 = IntToString(42, new char[] { '0', '1', '2' });

    // convert to hexadecimal
    string hex = IntToString(42, 
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                     'A', 'B', 'C', 'D', 'E', 'F'});
like image 58
Tilak Avatar answered Feb 02 '26 10:02

Tilak