将输入为十六进制的字符串转换为数字

时间:2022-12-09 07:47:21
将输入为十六进制的字符串转换为数字将输入为十六进制的字符串转换为数字
         /// <summary>
        /// 将输入为十六进制的字符串转换为数字
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        #region

        public byte[] StringToByte(string data)
        {
            List<byte> bdata = new List<byte>();
            char[] bufdata = data.ToCharArray();
            if (data.Length % 2 == 0)
            {
                byte buf1 = 0;

                for (int i = 0; i < data.Length - 1; )
                {
                    buf1 = OneStringtoByte(bufdata[i]);
                    buf1 <<= 4;
                    buf1 |= OneStringtoByte(bufdata[i + 1]);
                    bdata.Add(buf1);
                    i += 2;
                }
            }
            else
            {
                byte buf1 = 0;
                for (int i = 0; i < data.Length - 2; )
                {
                    buf1 = OneStringtoByte(bufdata[i]);
                    buf1 <<= 4;
                    buf1 |= OneStringtoByte(bufdata[i + 1]);
                    bdata.Add(buf1);
                    i += 2;
                }
                bdata.Add(OneStringtoByte(bufdata[bufdata.Length - 1]));
            }
            return bdata.ToArray();
        }
        public byte OneStringtoByte(char i)
        {
            switch (i)
            {
                case '0': return 0;
                case '1': return 1;
                case '2': return 2;
                case '3': return 3;
                case '4': return 4;
                case '5': return 5;
                case '6': return 6;
                case '7': return 7;
                case '8': return 8;
                case '9': return 9;
                case 'a': return 0x0a;
                case 'b': return 0x0b;
                case 'c': return 0x0c;
                case 'd': return 0x0d;
                case 'e': return 0x0e;
                case 'f': return 0x0f;
                case 'A': return 0x0a;
                case 'B': return 0x0b;
                case 'C': return 0x0c;
                case 'D': return 0x0d;
                case 'E': return 0x0e;
                case 'F': return 0x0f;
                default: return 0;
            }
        }
        #endregion
View Code