参照http://tool.chinaz.com/Tools/Unicode.aspx,用C#做一个编码转换的小工具。代码如下:
/// <summary>
/// 编码转换工具
/// 作者:Sunny906
/// 日期:2014-09-15
/// </summary>
public partial class TransformFrm : Form
{
public TransformFrm()
{
InitializeComponent();
}
//定义转换的枚举类型
private enum TransType
{
ASCIIToUnicode,
UnicodeToASCII,
UnicodeToCN,
CNToUnicode,
Clear
}
/// <summary>
/// 检查输入的内容是否为空
/// </summary>
/// <returns></returns>
private bool CheckSource()
{
if (this.rtbSource.Text.Length == 0)
{
return false;
}
return true;
}
/// <summary>
/// 根据指定的转换类型转换字符串
/// </summary>
/// <param name="type">转换类型</param>
private void TransText(TransType type)
{
if (type != TransType.Clear)
{
if (!CheckSource())
{
return;
}
}
string source = this.rtbSource.Text;
string dest = string.Empty;
switch (type)
{
case TransType.ASCIIToUnicode:
dest = string.Empty;
for (int i = 0; i < source.Length; i++)
{
dest += "&#" + ((int)source[i]).ToString() + ";";
}
break;
case TransType.UnicodeToASCII:
dest = string.Empty;
MatchCollection mc = Regex.Matches(source, "\\w+");
foreach (Match m in mc)
{
dest += ((char)int.Parse(m.Value)).ToString();
}
break;
case TransType.UnicodeToCN:
dest = string.Empty;
string[] arr = source.Replace("\\", "").Split('u');
for (int i = 1; i < arr.Length; i++)
{
dest += (char)int.Parse(arr[i], NumberStyles.HexNumber);
}
break;
case TransType.CNToUnicode:
dest = string.Empty;
for (int i = 0; i < source.Length; i++)
{
dest += "\\u" + ((int)source[i]).ToString("x");
}
break;
case TransType.Clear:
this.rtbDest.Clear();
break;
}
this.rtbDest.Text = dest;
}
private void btnASCIIToUnicode_Click(object sender, EventArgs e)
{
TransText(TransType.ASCIIToUnicode);
}
private void btnUnicodeToASCII_Click(object sender, EventArgs e)
{
TransText(TransType.UnicodeToASCII);
}
private void btnUnicodeToCN_Click(object sender, EventArgs e)
{
TransText(TransType.UnicodeToCN);
}
private void btnCNToUnicode_Click(object sender, EventArgs e)
{
TransText(TransType.CNToUnicode);
}
private void btnClear_Click(object sender, EventArgs e)
{
TransText(TransType.Clear);
}
}