Home  >  Article  >  Backend Development  >  .Net Chinese characters and Unicode encoding mutual conversion examples detailed introduction

.Net Chinese characters and Unicode encoding mutual conversion examples detailed introduction

黄舟
黄舟Original
2017-03-07 11:00:261549browse

下面小编就为大家带来一篇.Net(c#)汉字和Unicode编码互相转换实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

{"Tilte": "\u535a\u5ba2\u56ed", "Href": "http://www.jb51.net"}

经常遇到这样内容的json字符串,原来是把其中的汉字做了Unicode编码转换。

Unicode编码:

将汉字进行UNICODE编码,如:“王”编码后就成了“\王”,UNICODE字符以\u开始,后面有4个数字或者字母,所有字符都是16进制的数字,每两位表示的256以内的一个数字。而一个汉字是由两个字符组成,于是就很容易理解了,“738b”是两个字符,分别是“73”“8b”。但是在将 UNICODE字符编码的内容转换为汉字的时候,字符是从后面向前处理的,所以,需要把字符按照顺序“8b”“73”进行组合得到汉字。

 Unicode/汉字互转实现:

/// <summary>
/// <summary>
/// 字符串转Unicode
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>Unicode编码后的字符串</returns>
public static string String2Unicode(string source)
{
 byte[] bytes = Encoding.Unicode.GetBytes(source);
 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, &#39;0&#39;), bytes[i].ToString("x").PadLeft(2, &#39;0&#39;));
 }
 return stringBuilder.ToString();
}

/// <summary>
/// Unicode转字符串
/// </summary>
/// <param name="source">经过Unicode编码的字符串</param>
/// <returns>正常字符串</returns>
public static string Unicode2String(string source)
{
 return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
     source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
}

 以上就是.Net汉字和Unicode编码互相转换实例详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn