aspnet2014-07-22 18:48:10 4904
unicode是一种使用广泛的计算机字符编码,他的产生是为了解决传统的字符编码的局限性。下面说说在.net平台下,怎样对字符进行unicode编码和解码。
/// <summary> /// Unicode编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string BaseUnicode(string str) { if (str.Length == 0) return ""; byte[] mBytes = Encoding.Unicode.GetBytes(str); string returnString = ""; for (int index = 0; index < mBytes.Length; index = 2) { returnString = "u" mBytes[index 1].ToString("x").PadLeft(2, '0') mBytes[index].ToString("x").PadLeft(2, '0'); } return returnString; }
/// <summary> /// Unicode解码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string UnBaseUnicode(string str) { StringBuilder mStringBuilder = new StringBuilder(); MatchCollection mMatchCollection = Regex.Matches(str, "([w] )|(u([w]{4}))"); if (mMatchCollection != null && mMatchCollection.Count > 0) { foreach (Match mMatch in mMatchCollection) { string value = mMatch.Value; if (value.StartsWith("u")) { string subString = value.Substring(2); byte[] bytesValue = new byte[2]; int subStringBefore = System.Convert.ToInt32(subString.Substring(0, 2), 16); int subStringAfter = System.Convert.ToInt32(subString.Substring(2), 16); bytesValue[0] = (byte)subStringAfter; bytesValue[1] = (byte)subStringBefore; mStringBuilder.Append(Encoding.Unicode.GetString(bytesValue)); } else { mStringBuilder.Append(value); } } } return mStringBuilder.ToString(); }
彭亚欧个人博客原创文章,转载请注明出处
文章关键词:ASP.NETUnicode转汉字,C#Unicode编码解码,Unicode编解码
文章固定链接:https://www.pengyaou.com/legendsz/server/aspnet/NTc=.html
上一篇 javascript监测键盘按键
下一篇 CSS3立方体柜子