Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any built-in way to convert an integer to a string (of any base) in C#?

Tags:

c#

base

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?

like image 273
Jedidja Avatar asked Sep 18 '08 18:09

Jedidja


1 Answers

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.

like image 159
Guvante Avatar answered Oct 17 '22 05:10

Guvante