[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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值