汉字转Unicode码,涉及的知识点:
1、“x”则代表十六进制,“x4”代表十六进制表示的可控制长度,如果长度不够,则用前导的0填补。
2、Unicode写法:在表示一个Unicode的字符时,通常会用“U+”然后紧接着一组十六进制的数字来表示这一个字符。
3、 ASCII 码(American Standard Code for Information Interchange,全称美国信息交换标准码)
基本的 ASCII 字符集共有 128 个字符,其中有 96 个可打印字符,包括常用的字母、数字、标点符号等,另外还有 32 个控制字符。
0~31及127(共33个)是控制字符或通信专用字符(其余为可显示字符),如控制符:LF(换行)、CR(回车)、FF(换页)、DEL(删除)、BS(退格)、BEL(振铃)等;通信专用字符:SOH(文头)、EOT(文尾)、ACK(确认)等;ASCII值为8、9、10和13分别转换为退格、制表、换行和回车字符。它们并没有特定的图形显示,但会依不同的应用程序而对文本显示有不同的影响。
32~126(共95个)是字符(32sp是空格),其中48~57为0到9十个阿拉伯数字,65~90为26个大写英文字母,97~122为26个小写字母,其余为一些标点符号、运算符号等。
//转成16进制->Unicode 小端
public static string GetUnicode(string ChinaStrText)
{
string result = "";
for (int i = 0; i < ChinaStrText.Length; i++)
{
if ( (int)ChinaStrText[i] < 127) //(int)ChinaStrText[i] > 32 &&
{
result += string.Format("{0:x2}", (int)ChinaStrText[i]) + "00";
}
else
{
string temp = string.Format("{0:x4}", (int)ChinaStrText[i]);
result += temp.Substring(2, 2) + temp.Substring(0, 2);
}
}
return result;
}
将Unicode码转成汉子字符串
/// <summary>
/// 将Unicode编码转换为汉字字符串
/// </summary>
/// <param name="UnicodeStr">Unicode编码字符串</param>
/// <returns>汉字字符串</returns>
public static string ToGB2312(string UnicodeStr)
{
StringBuilder rest = new StringBuilder();
for(int i =0 ; i < UnicodeStr.Length/4; i++)
{
string SplitWord = UnicodeStr.Substring(i * 4, 4);
byte[] codes = new byte[2];
int code = Convert.ToInt32(SplitWord.Substring(0, 2), 16);
int code2 = Convert.ToInt32(SplitWord.Substring(2), 16);
codes[0] = (byte)code;
codes[1] = (byte)code2;
rest.Append(Encoding.Unicode.GetString(codes));
}
return rest.ToString();
}