如何将字符串转换为十六进制字符串

///
        /// 将指定编码的字符串转换成十六进制
        ///

        /// 原串
        /// 原串编码
        /// 十六进制串
        public static string ConvertStringToHex(string src, Encoding encode)
        {
            byte[] buffer = encode.GetBytes(src);
            string hex = string.Empty;
            for (int i = 0; i < buffer.Length; i++)
            {
                string t=buffer[i].ToString("x");
                if (t.Length == 1) t = "0" + t;
                hex += t;
            }
            return hex;
        }

..

///
        /// 将十六进制串转换为指定编码的字符串
        ///

        /// 十六进制串
        /// 要转换成的字符串的编码
        /// 指定编码的字符串
        public static string ConvertStringFromHex(string hex, Encoding encode)
        {
            string src = string.Empty;
            int len = hex.Length / 2;
            byte[] buffer = new byte[len];
            for (int i = 0; i < len; i++)
            {
                buffer[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            src = encode.GetString(buffer);
            return src;
        }

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