1. 程式人生 > >字串十六進位制轉ASCII碼

字串十六進位制轉ASCII碼

  /// <summary>
        /// 將一條十六進位制字串轉換為ASCII
        /// </summary>
        /// <param name="hexstring">一條十六進位制字串</param>
        /// <returns>返回一條ASCII碼</returns>
        public static string HexStringToASCII(string hexstring)
        {
            string result = Regex.Replace(hexstring, @".{2}", "$0 ");
            byte[] bt = HexStringToBinary(result);
            string lin = "";
            for (int i = 0; i < bt.Length; i++)
            {
                lin = lin + bt[i] + " ";
            }


            string[] ss = lin.Trim().Split(new char[] { ' ' });
            char[] c = new char[ss.Length];
            int a;
            for (int i = 0; i < c.Length; i++)
            {
                a = Convert.ToInt32(ss[i]);
                c[i] = Convert.ToChar(a);
            }

            string b = new string(c);
            return b;
}

 /// <summary>
        /// 16進位制字串轉換為二進位制陣列
        /// </summary>
        /// <param name="hexstring">用空格切割字串</param>
        /// <returns>返回一個二進位制字串</returns>
        public static byte[] HexStringToBinary(string hexstring)
        {

            string[] tmpary = hexstring.Trim().Split(' ');
            byte[] buff = new byte[tmpary.Length];
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = Convert.ToByte(tmpary[i], 16);
            }
            return buff;
        }