在.NET Framework中,System.Convert类中提供了较为全面的各种类型、数值之间的转换功能。其中的两个方法可以轻松的实现各种进制的数值间的转换:Convert.ToInt32(string value, int fromBase):可以把不同进制数值的字符串转换为数字,其中fromBase参数为进制的格式,只能是2、8、10及16:如Convert.ToInt32(”0010”,2)执行的结果为2;Convert.ToString(int value, int toBase):可以把一个数字转换为不同进制数值的字符串格式,其中toBase参数为进制的格式,只能是2、8、10及16:如Convert.ToString(2,2)执行的结果为”0010”现在我们做一个方法实现各种进制间的字符串自由转换:选把它转成数值型,然后再转成相应的进制的字符串:public string ConvertString(string value, int fromBase, int toBase){ int intValue = Convert.ToInt32(value, fromBase); return Convert.ToString(intValue, toBase); }其中fromBase为原来的格式toBase为将要转换成的格式
using System;
class Test { static void Main() { foreach (int a in new int [] {0, 123456789, -123456789}) Console.WriteLine("dec:{0,10} hex:{1,8} bin:{2,32}", a, a.ToString("X"), Int2Bin(a)); }
public static string Int2Bin(int n) { uint un = (uint)n; string s = null, t = null; for (; un > 0; un /= 2) s += un % 2; if (s == null) s = "0"; for (int i = s.Length - 1; i >= 0; i--) t += s[i]; return t; } }
但是浮点的不能这样做,好像没有现成的方法,得用浮点数转二进制的那个除法那样转。
}其中fromBase为原来的格式toBase为将要转换成的格式
class Test {
static void Main() {
foreach (int a in new int [] {0, 123456789, -123456789})
Console.WriteLine("dec:{0,10} hex:{1,8} bin:{2,32}", a, a.ToString("X"), Int2Bin(a));
}
public static string Int2Bin(int n)
{
uint un = (uint)n;
string s = null, t = null;
for (; un > 0; un /= 2) s += un % 2;
if (s == null) s = "0";
for (int i = s.Length - 1; i >= 0; i--) t += s[i];
return t;
}
}
运行结果如下:
dec: 0 hex: 0 bin: 0
dec: 123456789 hex: 75BCD15 bin: 111010110111100110100010101
dec:-123456789 hex:F8A432EB bin:11111000101001000011001011101011