是否有一个整数转换为C#中(任何基地)字符串任何内置的方式吗? [英] Is there any built-in way to convert an integer to a string (of any base) in C#?
本文介绍了是否有一个整数转换为C#中(任何基地)字符串任何内置的方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Convert.ToString()只允许基值2,8,10,16和一些奇怪的原因;在那里提供2和16之间的任何基地的一些模糊的方式?
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?
推荐答案
大概消除某人键入7,而不是8由于任意基地的用途是少数(但并非不存在)。
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.
这篇关于是否有一个整数转换为C#中(任何基地)字符串任何内置的方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文