在日常编程中,常常需要把中文转换为unicode码,我特编写了下列的小程序来转换,希望对大家有用:
StringBuilder sb = new StringBuilder();//Unicode
StringBuilder sa = new StringBuilder();//UTF-8
string s1;
string s2;
for(int i=0;i<sCode.length();i++)
byte[] bt = System.Text.Encoding.Unicode.GetBytes(sCode.Text.Substring(i,1));
if(bt.Length>1)//判断是否汉字
{
s1=Convert.ToString((short)(bt[1] - '\0'),16);//转化为16进制字符串
s2=Convert.ToString((short)(bt[0] - '\0'),16);//转化为16进制字符串
s1=(s1.Length==1?“0”:“”)+s1;//不足位补0
s2=(s2.Length==1?“0”:“”)+s2;//不足位补0
sa.Append("&#"+Convert.ToInt32(s1+s2,16)+“;”);
sb.Append("\\u"+s1+s2);
}
}
Clipboard.SetDataObject(sb.ToString());
txtUTF8.Text = sa.ToString();
txtUnicode.Text = sb.ToString();