6

Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?

Jedidja
  • 16,610
  • 17
  • 73
  • 112
  • The choice of bases is not arbitrary. Your PC is constantly converting from base 2 (its internal binary system) to the human readable base 10. Base 8 and 16 are very easy to convert to and from base 2 and are often used so a computer AND a human can read the value (e.g. GUIDs) –  Aug 12 '09 at 07:02

3 Answers3

6

Probably to eliminate someone typing a 7 instead of an 8, since the uses for arbitrary bases are few (But not non-existent).

Here is an example method that can do arbitrary base conversions. You can use it if you like, no restrictions.

string ConvertToBase(int value, int toBase)
{
     if (toBase < 2 || toBase > 36) throw new ArgumentException("toBase");
     if (value < 0) throw new ArgumentException("value");

     if (value == 0) return "0"; //0 would skip while loop

     string AlphaCodes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

     string retVal = "";

     while (value > 0)
     {
          retVal = AlphaCodes[value % toBase] + retVal;
          value /= toBase;
     }

     return retVal;
}

Untested, but you should be able to figure it out from here.

Guvante
  • 18,775
  • 1
  • 33
  • 64
0
//untested  -- public domain
// if you do a lot of conversions, using StringBuilder will be 
// much, much more efficient with memory and time than using string
// alone.

string toStringWithBase(int number, int base)
    { 
    if(0==number) //handle corner case
        return "0";
    if(base < 2)
        return "ERROR:  Base less than 2";

    StringBuilder buffer = new StringBuilder(); 

    bool negative = (number < 0) ? true : false;
    if(negative)
        {
        number=-number;
        buffer.Append('-');
        }

    int digits=0;
    int factor=1;

    int runningTotal=number;
    while(number > 0)
       {
       number = number/base;
       digits++;
       factor*=base;
       }
    factor = factor/base;

    while(factor >= 1)
       {
       int remainder = (number/factor) % base;

       Char out = '0'+remainder;
       if(remainder > 9)
           out = 'A' + remainder - 10;
       buffer.Append(out);
       factor = factor/base;
       }

    return buffer.ToString
    }
Brian
  • 8,454
  • 5
  • 27
  • 30
-3
string foo = Convert.ToString(myint,base);

http://msdn.microsoft.com/en-us/library/14kwkz77.aspx

EDIT: My bad, this will throw an argument exception unless you pass in the specified bases (2, 8, 10, and 16)

Your probably SOL if you want to use a different base (but why???).

FlySwat
  • 172,459
  • 74
  • 246
  • 311