字符和十六进制码的互换
private string ToUnicodeString(string s)
{
StringBuilder sb = new StringBuilder();
byte[] bytes = Encoding.Unicode.GetBytes(s);
for (int i = 0; i
{
sb.Append(“\\u”);
sb.Append(bytes[i + 1].ToString(“x2”));
sb.Append(bytes[i].ToString(“x2”));
i += 2;
}
return sb.ToString();
}
private string ToNormalString(string input)
{
string pattern = “\\\\u([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})”;
Match match = System.Text.RegularExpressions.Regex.Match(input,pattern);
System.Collections.ArrayList numlist = new System.Collections.ArrayList();
while(match.Success)
{
string s = match.Groups[2].Value;
byte num = byte.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
numlist.Add(num);
s = match.Groups[1].Value;
num = byte.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
numlist.Add(num);
match = match.NextMatch();
}
byte[] bytes = new byte[numlist.Count];
numlist.CopyTo(bytes);
string result = Encoding.Unicode.GetString(bytes);
return result;
}
调用结果:
ToUnicodeString(“Hello World”); –> \u0048\u0065\u006c\u006c\u006f\u002c\u0020\u0057\u006f\u0072\u006c\u0064\u0021
string str = @”\u0048\u0065\u006c\u006c\u006f\u002c\u0020\u0057\u006f\u0072\u006c\u0064\u0021″;
ToNormalString(str); –> Hello World!