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

前端 未结 6 2028
梦毁少年i
梦毁少年i 2020-12-20 20:02

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?

6条回答
  •  无人及你
    2020-12-20 20:38

    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.

提交回复
热议问题