博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

汉字转Unicode小工具

Posted on 2011-12-20 12:04  Honor  阅读(2425)  评论(2)    收藏  举报

笔者今天在开发一个自定义弹出对话框的时候,发现系统默认引用的js文件是采用UTF-8编码的,这样导致对话框内容都是乱码。

如下图

 

本来打算改js文件的引用方式为:charset="utf-8",但是这个对话框引用很繁琐,找起来很麻烦,思量了下决定把中文改成Unicode编码

的字符这样就不会出现乱码了。

效果如图:

 

 

但是有个问题,汉子转Unicode的工具网上没搜到一个很好的,最后决定自己写一个这样的工具取名为:GBToUnicode

 

 以下是源码,方便大家查阅

 1 using System;
2 using System.Text;
3 using System.Windows.Forms;
4 using System.Text.RegularExpressions;
5
6 namespace GBToUnicode
7 {
8 public partial class Form1 : Form
9 {
10 public Form1()
11 {
12 InitializeComponent();
13 }
14
15 private void btnGB_Click(object sender, EventArgs e)
16 {
17 txbGB.Text = UnicodeToGB(txbUnicode.Text.Trim());
18 }
19
20 private void btnUnicode_Click(object sender, EventArgs e)
21 {
22 txbUnicode.Text = GBToUnicode(txbGB.Text.Trim());
23 }
24
25
26 /// <summary>
27 /// 将汉字转换为Unicode
28 /// </summary>
29 /// <param name="strGB">要转换的字符串</param>
30 /// <returns></returns>
31 public static string GBToUnicode(string strGB)
32 {
33 byte[] bytes = System.Text.Encoding.Unicode.GetBytes(strGB);
34 string lowCode = "", tmpChar = "";
35
36 for (int i = 0; i < bytes.Length; i++)
37 {
38 if (i % 2 == 0)
39 {
40 tmpChar = System.Convert.ToString(bytes[i], 16);//取出元素4编码内容(两位16进制)
41 if (tmpChar.Length < 2)
42 tmpChar = "0" + tmpChar;
43 }
44 else
45 {
46 string mytemp = Convert.ToString(bytes[i], 16);
47 if (mytemp.Length < 2)
48 mytemp = "0" + mytemp;
49 lowCode = lowCode + @"\u" + mytemp + tmpChar;//取出元素4编码内容(两位16进制)
50 }
51 }
52 return lowCode;
53 }
54
55 /// <summary>
56 /// 将Unicode转换为汉字
57 /// </summary>
58 /// <param name="name">要转换的字符串</param>
59 /// <returns></returns>
60 public string UnicodeToGB(string text)
61 {
62
63 MatchCollection mc = Regex.Matches(text, "([\\w]+)|(\\\\u([\\w]{4}))");
64 if (mc != null && mc.Count > 0)
65 {
66 StringBuilder sb = new StringBuilder();
67 foreach (Match m2 in mc)
68 {
69 string v = m2.Value;
70 string word = v.Substring(2);
71 byte[] codes = new byte[2];
72 int code = Convert.ToInt32(word.Substring(0, 2), 16);
73 int code2 = Convert.ToInt32(word.Substring(2), 16);
74 codes[0] = (byte)code2;
75 codes[1] = (byte)code;
76 sb.Append(Encoding.Unicode.GetString(codes));
77 }
78 return sb.ToString();
79 }
80 else
81 {
82 return text;
83 }
84 }
85 }
86 }

 

 

下载地址:GBToUnicode