Unicode编码与汉字字符串的转换
2013-12-13 17:00
399 查看
/// <summary>
/// 汉字转换为Unicode编码
/// </summary>
/// <param name="str">要编码的汉字字符串</param>
/// <returns>Unicode编码的的字符串</returns>
public static string ToUnicode(string str)
{
byte[] bts = Encoding.Unicode.GetBytes(str);
string r = "";
for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
return r;
}
/// <summary>
/// 将Unicode编码转换为汉字字符串
/// </summary>
/// <param name="str">Unicode编码字符串</param>
/// <returns>汉字字符串</returns>
public static string ToGB2312(string str)
{
string r = "";
MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
byte[] bts = new byte[2];
foreach (Match m in mc)
{
bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
r += Encoding.Unicode.GetString(bts);
}
return r;
}
/// 汉字转换为Unicode编码
/// </summary>
/// <param name="str">要编码的汉字字符串</param>
/// <returns>Unicode编码的的字符串</returns>
public static string ToUnicode(string str)
{
byte[] bts = Encoding.Unicode.GetBytes(str);
string r = "";
for (int i = 0; i < bts.Length; i += 2) r += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
return r;
}
/// <summary>
/// 将Unicode编码转换为汉字字符串
/// </summary>
/// <param name="str">Unicode编码字符串</param>
/// <returns>汉字字符串</returns>
public static string ToGB2312(string str)
{
string r = "";
MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
byte[] bts = new byte[2];
foreach (Match m in mc)
{
bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
r += Encoding.Unicode.GetString(bts);
}
return r;
}
相关文章推荐
- 把unicode编码的十六进制字符串转换为汉字(Python2.7)
- iOS把字符串汉字转换成UTF-8编码
- Python 普通str字符串 和 unicode 字符串 及字符串编码探测、转换
- java xx.properties文件中汉字UNICODE编码的正则表达式转换为汉字
- C#,JavaScript 汉字转换为Unicode编码 Unicode编码转换为汉字
- 【小工具类】Unicode字符串转换成汉字
- C#中将UNICODE编码后的字符转换为汉字
- Ansi、Unicode、UTF8等编码字符串之间的转换和写入文本文件(学习中……)
- JavaScript汉字Unicode编码相互转换
- 转换汉字为unicode形式的字符串和转换unicode形式字符串转换成汉字
- &#x(unicode编码后的汉字)JS转换方法
- Java:转换汉字为unicode形式的字符串和转换unicode形式字符串转换成汉字
- .Net(c#)汉字和Unicode编码互相转换
- Python中unicode编码的字符串和其他格式的字符串之间进行转换
- 用AutoHotkey做汉字到Unicode字符串的转换
- python str方法转换为字符串 对于Unicode会调用系统默认编码
- JavaScript中字符串与Unicode编码互相转换的实现方法
- 根据Unicode编码用C#语言把它转换成汉字的代码
- Ansi、Unicode、UTF8等编码字符串之间的转换和写入文本文件(学习中……)
- PHP将汉字转换成Unicode编码的函数