.NET是否具有与PHP的base_convert等效的本机函数,还是需要编写自己的函数?我想从任何基数转换为任何其他基数 - 其中'to'基数或'from'基数可以是任何整数2-36.
PHP函数示例:base_convert($ number_to_convert,$ from_base,$ to_base)
// convert 101 from binary to decimal echo base_convert('101', 2, 10); // 5
正如Luke在Jon Skeet的回答中所指出的那样:Convert.ToString无法处理任何基数的转换,只有2,8,10和16
更新:显然,答案是:不,没有本地方式.下面,Erik展示了一种方法.另一个实现是:http://www.codeproject.com/KB/macros/Convert.aspx
编辑:这个答案非常方便,但只适用于基地2,8,10和16
你可以使用Convert.ToInt32(text, base)
然后Convert.ToString(number, base)
:
using System; class Test { static void Main() { int number = Convert.ToInt32("101", 2); string text = Convert.ToString(number, 10); Console.WriteLine(text); // Prints 5 } }
如果您要转换到基数10或从基数10转换,则无需指定 - 这是默认值.
请注意,这仅适用于基数2,8,10和16.如果您还需要其他任何内容,则必须编写自己的解析器/格式化程序.
这里有一些代码可以将整数转换为最多36的任意基数,并将基础x值的字符串表示转换为整数(给定基数):
class Program { static void Main(string[] args) { int b10 = 123; int targetBase = 5; string converted = ConvertToBase(b10, targetBase); int convertedBack = ConvertFromBase(converted, targetBase); string base3 = "212210"; string base7 = ConvertFromBaseToBase(base3, 3, 7); Console.WriteLine(converted); Console.WriteLine(convertedBack); Console.WriteLine(base7); Console.ReadLine(); } private const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static string ConvertToBase(int b10, int targetBase) { if (targetBase < 2) throw new ArgumentException("Target base must be greater than 2.", "targetBase"); if (targetBase > 36) throw new ArgumentException("Target base must be less than 36.", "targetBase"); if (targetBase == 10) return b10.ToString(); StringBuilder result = new StringBuilder(); while (b10 >= targetBase) { int mod = b10 % targetBase; result.Append(chars[mod]); b10 = b10 / targetBase; } result.Append(chars[b10]); return Reverse(result.ToString()); } private static int ConvertFromBase(string bx, int fromBase) { if (fromBase < 2) throw new ArgumentException("Base must be greater than 2.", "fromBase"); if (fromBase > 36) throw new ArgumentException("Base must be less than 36.", "fromBase"); if (fromBase == 10) return int.Parse(bx); bx = Reverse(bx); int acc = 0; for (int i = 0; i < bx.Length; i++) { int charValue = chars.IndexOf(bx[i]); acc += (int)Math.Pow(fromBase, i) * charValue; } return acc; } public static string ConvertFromBaseToBase(string bx, int fromBase, int toBase) { int b10 = ConvertFromBase(bx, fromBase); return ConvertToBase(b10, toBase); } public static string Reverse(string s) { char[] charArray = new char[s.Length]; int len = s.Length - 1; for (int i = 0; i <= len; i++) charArray[i] = s[len - i]; return new string(charArray); } }
如果你不关心显示这些值,你可以在你的字符集中使用扩展字符 - 如果你坚持使用简单的ascii,理论上你可以有base256值.除此之外,我建议不要使用字符,而是使用其他一些可识别的唯一值 - 尽管我没有太多看到它的价值.