c# 字符串与16进制ASCII码相到转换

1.普通字符串转16进制ASCII码

//普通字符串转16进制ASCII码        
public static string toASCII(string code)
        {
            char[] cs = code.ToCharArray();//先转字节数组
            string Hstr = null;
            for (int l = 0; l < cs.Length; l++)
            {
                Hstr += ((int)cs[l]).ToString("X");
            }
            //System.Console.WriteLine(Hstr);
            return Hstr;
        }

2.16进制ASCII码转普通字符串

 public static string getASCIItoStr(string str)
        {
            byte[] bb = Hex2Bytes(str, false);
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
            string strCharacter = asciiEncoding.GetString(bb);
            Console.WriteLine(strCharacter);
            return strCharacter;
        }
//先将16进制ASCII码转字节数组
        public static byte[] Hex2Bytes(string sHex, bool isExchange)
        {
            if (sHex == null || sHex.Length == 0)
                return null;
            sHex = sHex.Length % 2 == 0 ? sHex : "0" + sHex;
            byte[] bRtns = new byte[sHex.Length / 2];
            for (int i = 0; i < bRtns.Length; i++)
            {
                if (isExchange)
                    bRtns[bRtns.Length - 1 - i] = Convert.ToByte(sHex.Substring(i * 2, 2), 16);
                else
                    bRtns[i] = Convert.ToByte(sHex.Substring(i * 2, 2), 16);
            }
            return bRtns;
        }
    }

 

你可能感兴趣的:(C#,c#,开发语言)