using System;
using System.Text;
using System.Text.RegularExpressions;
/// <summary> /// 将字节数组转为字符串 /// </summary> /// <param name="b">字节数组</param> /// <param name="e">编码,默认为Default</param> /// <returns></returns> internal static string ByteToString(byte[] b, Encoding e = null) { if (e == null) { e = Encoding.Default; } string result = e.GetString(b); return result; } /// <summary> /// 将字符串转为字节数组 /// </summary> /// <param name="s">字符串</param> /// <param name="e">编码,默认为Default</param> /// <returns></returns> internal static byte[] StringToByte(string s, Encoding e = null) { if (e == null) { e = Encoding.Default; } byte[] b = e.GetBytes(s); return b; } /// <summary> /// 字符串转Unicode码 /// </summary> /// <returns>Unicode码</returns> /// <param name="value">字符串</param> internal static string StringToUnicode(string value) { byte[] bytes = Encoding.Unicode.GetBytes(value); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < bytes.Length; i += 2) { // 取两个字符,每个字符都是右对齐。 stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0')); } return stringBuilder.ToString(); } /// <summary> /// Unicode转String /// </summary> /// <param name="SourceString"></param> /// <returns></returns> internal static string UnicodeToString(string SourceString) { Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})"); return reg.Replace(SourceString, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); }); } /// <summary> /// Unicode转中文 /// </summary> /// <returns>中文</returns> /// <param name="text">Unicode码</param> internal static string UnicodeToChinese(string text) { MatchCollection mc = Regex.Matches(text, "\\\\u([\\w]{4})"); if (mc != null && mc.Count > 0) { foreach (Match m2 in mc) { string v = m2.Value; string word = v.Substring(2); byte[] codes = new byte[2]; int code = Convert.ToInt32(word.Substring(0, 2), 16); int code2 = Convert.ToInt32(word.Substring(2), 16); codes[0] = (byte)code2; codes[1] = (byte)code; text = text.Replace(v, Encoding.Unicode.GetString(codes)); } } return text; }
评论前必须登录!
注册