汉字与十六进制之间的相互转换

时间:2022-12-16 22:43:16

1. 汉字转十六进制

   

public static string GBToUnicode(string text) {

  byte[] bytes = System.Text.Encoding.Unicode.GetBytes(text);

  string lowCode = "", temp = "";

   for (int i = 0; i < bytes.Length; i++) {

       if (i % 2 == 0) {

            temp = System.Convert.ToString(bytes[i], 16);//取出元素4编码内容(两位16进制)

           if (temp.Length < 2) temp = "0" + temp;

        } else {

            string mytemp = Convert.ToString(bytes[i], 16);

          if (mytemp.Length < 2) mytemp = "0" + mytemp;

          lowCode = lowCode + @"\u" + mytemp + temp;//取出元素4编码内容(两位16进制)

        }

        }

       return lowCode;

}

 

2. 十六进制与汉字之间的相互转换

/// <summary>
        /// 汉字转换为Unicode编码
        /// </summary>
        /// <param name="str">要编码的汉字字符串</param>
        /// <returns>Unicode编码的的字符串</returns>
        public static string ToUnicode(string str)
        {
            byte[] bts = Encoding.Unicode.GetBytes(str);
            string r = "";
            for (int i = 0; i < bts.Length; i += 2) r += "" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
            return r;
        }
        /**/
        /// <summary>
        /// 将Unicode编码转换为汉字字符串
        /// </summary>
        /// <param name="str">Unicode编码字符串</param>
        /// <returns>汉字字符串</returns>
        public static string ToGB2312(string str)
        {
            string r = "";
            
            MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            byte[] bts = new byte[2];
            foreach (Match m in mc)
            {
                bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
                bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
                r += Encoding.Unicode.GetString(bts);
            }
            return r;
        }

 

3. 字符串转十六进制

buffer[i] = (byte)Convert.ToByte(str.Substring(i, 2), 16);

4. 十六进制转字符串

strRecieve += Convert.ToString(buffer[i], 16).PadLef(2, '0').PadRight(3, ' ').ToUpper();

    或:

strRecieve += buffer[i].ToString("X2").PadRight(3,' '); 

5. 字节数组转十六进制

/// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }