[C#] 2, 8, 10, 16 进制数之间的相互转换

Stackoverflow 上的答案:

public static string AnyConverter(string number, int fromBase, int toBase)
{
    string result;
    try
    {
        result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
    }
    catch (Exception exp)
    {
        result = exp.Message;
    }
    return result;
}

static void Main(string[] args)
{
    // 测试:
    Console.WriteLine("100 2 -> 10 result: " + AnyConverter("100", 2, 10));
    Console.WriteLine("100 10 -> 2 result: " + AnyConverter("100", 10, 2));
    Console.WriteLine("0xF 16 -> 2 result: " + AnyConverter("0xF", 16, 2));
    Console.WriteLine("090 8 -> 10 result: " + AnyConverter("090", 8, 10));
    Console.WriteLine("15 10 -> 16 result: " + AnyConverter("15", 10, 16));
}

输出:

100 2 -> 10 result: 4
100 10 -> 2 result: 1100100
0xF 16 -> 2 result: 1111
090 8 -> 10 result: 字符串的末尾有其他无法分析的字符。// 9改成1就ok,8进制
15 10 -> 16 result: f

如果不用这种非常简洁的函数,就要自己动手写 12个函数出来。表示8进制和16进制的0和0x加不加都可以,结果都正确。


[1] https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81741917