十六进制字符串转十进制

发布时间 2023-06-10 09:56:02作者: 丹心石

十六进制转换在上位机通讯中必然会用到:

  • 字符串格式的十六进制,如011E,这里是2个字节,十六进制高位在前,低位在后,而数组存储则相反,前面为0,后面为高位
    如"011E" 01为高位,1E为低位,而字符串数组存储则是data="011E" data[0]='0' data[1]='1' data[2]='1' data[3]='E',因此在逐为相加时可以从高索引为开始取,示例如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static int getdata(string hex) {
            int d=0;
            int m=1;
            for (int i = hex.Length - 1; i > 0; i--) {
                 d += GetChar(hex[i].ToString())*m;
                m = m * 16;
            }
            return d;
        }
        private static int GetChar(string ss) {
            switch (ss) {
                case "A":
                    return 10;
                case "B":
                    return 11;
                case "C":
                    return 12;
                case "D":
                    return 13;
                case "E":
                    return 14;
                case "F":
                    return 15;
                default:
                    return Convert.ToInt32(ss);
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("十六转10进制测试");
            Console.WriteLine($"0014={getdata("0014")}");  //输出结果为  20
            Console.ReadKey();
        }
    }
}

image