字符串转化为16进制内容

 小工具

        public static string Encode(string s) { 
            byte[] data = Encoding.UTF8.GetBytes(s); 
            StringBuilder result = new StringBuilder(data.Length * 8); 
            foreach (byte b in data) { 
                result.Append("\\x" + Convert.ToString(b, 16).PadLeft(2, '0').ToUpper()); 
            } 
            return result.ToString(); 
        }

        public static string Decode(string s) { 
            System.Text.RegularExpressions.CaptureCollection cs = System.Text.RegularExpressions.Regex.Match(s, @"([\\xa-fA-F0-9]{4})+").Groups[1].Captures; 
            byte[] data = new byte[cs.Count]; 
            for (int i = 0; i < cs.Count; i++) { 
                data[i] = Convert.ToByte(cs[i].Value.Replace("\\x",""), 16);
            } 
            return Encoding.UTF8.GetString(data, 0, data.Length);
        }

posted on 2013-05-30 13:02  relax  阅读(325)  评论(0编辑  收藏  举报