将以字符char格式描述的十六进制转换为Byte

若某个十六进制数(如0xE9)是以两个字符char进行描述的(“E"和"9”),现需要将其转换为一个byte。
首先对单个字符(如“E”)进行转换,通过ASCII码转换表做差得出其真实值:

//将char变量转换为数字整型
        private byte ConvertCharDataToByte(char data)
        {
            short asciiValue = (short)data;//此处强制转换,得出该字符的ASCII码
            if (asciiValue > 0x40) //该字符为字母
            {
                return (byte)(asciiValue - 55);
            }
            else//该字符为数字
            {
                return (byte)(asciiValue - 48);
            }
        }

将两个char字符计算得出真实值之后,再进行合并:

 //将两个char合并为一个Byte
        private byte CombineCharToByte(char[] charArray)//传参数组长度:2
        {
            int dataInt1 = ConvertCharDataToByte(charArray[0]);
            int dataInt2 = ConvertCharDataToByte(charArray[1]);

            byte objData = (byte)(dataInt1 * 16 + dataInt2);
            return objData;
        }

你可能感兴趣的:(C#)