c# 字符串转16进制及16进制转换成字符串

string chaStr = StringToHexString(str, Encoding.UTF8);   //字符串转16进制
string yStr = HexStringToString(chaStr, Encoding.UTF8); //16进制转换成字符串
/// <summary>
        /// 字符串转16进制
        /// </summary>
        /// <param name="str">
        /// <param name="encode">
        /// <returns></returns>
        public string StringToHexString(string str, Encoding encode)
        {
            byte[] b = encode.GetBytes(str); 
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < b.Length; i++) 
            {
                result.Append(Convert.ToString(b[i], 16));
            }
            return result.ToString();
        }
        /// <summary>
        /// 16进制转换成字符串
        /// </summary>
        /// <param name="hs">
        /// <param name="encode">
        /// <returns></returns>
        public string HexStringToString(string hs, Encoding encode)
        {
            StringBuilder strTemp = new StringBuilder() ;
            byte[] b = new byte[hs.Length / 2];
            for (int i = 0; i < hs.Length / 2; i++)
            {
                strTemp.Clear();
                strTemp.Append(hs.Substring(i * 2, 2));
                b[i] = Convert.ToByte(strTemp.ToString(), 16);
            }         
            return encode.GetString(b);
        }

 

UrlEncoded: HttpUtility.UrlEncode

UrlEncodedUnicode: HttpUtility.UrlEncodeUnicode

UrlPathEncoded: HttpUtility.UrlPathEncode

EscapedDataString: Uri.EscapeDataString

EscapedUriString: Uri.EscapeUriString

HtmlEncoded: HttpUtility.HtmlEncode

HtmlAttributeEncoded: HttpUtility.HtmlAttributeEncode

HexEscaped: Uri.HexEscape

 

posted @ 2023-03-16 11:03  流氓大菠萝  阅读(828)  评论(0编辑  收藏  举报