在日常编程中,常常需要把中文转换为unicode码
常常需要把中文转换为unicode码:
StringBuilder sb = new StringBuilder();//Unicode
StringBuilder sa = new StringBuilder();//UTF-8
string s1;
string s2;
for(int i=0;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();
StringBuilder sb = new StringBuilder();//Unicode
StringBuilder sa = new StringBuilder();//UTF-8
string s1;
string s2;
for(int i=0;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();