您的位置:首页 - .NET
.NET字符串编码解码的方式
几个重要的方法:
Encoding.UTF8.GetString(byte[])
Encoding.UTF8.GetBytes(String)
Encoding.GetEncoding(String).GetBytes(String)
Encoding.GetEncoding(String).GetString(byte[])
Convert.ToString(byte,int)
Convert.ToByte(String,int)




class Program
{
static void Main(string[] args)
{
string str = "柯乐义网";
//Gb2312编码
Console.WriteLine(GB2312(str));
//GB2312解码
Console.WriteLine(DeGB2312(GB2312(str)));
//UTF8编码
Console.WriteLine(EnUTF8(str));
//UTF8解码
Console.WriteLine(DeUTF8(EnUTF8(str)));
Console.ReadKey();
}
/// <summary>
/// GB2312编码
/// </summary>
/// <param name="str">待编码字符</param>
/// <returns>编码结果</returns>
public static string GB2312(string str)
{
StringBuilder sb = new StringBuilder();
//GB2321的编码方式
byte[] byStr = System.Text.Encoding.GetEncoding ("GB2312").GetBytes(str);
for (int i = 0; i < byStr.Length; i++)
{
//转换为16进制方式 可选2,8,10,16进制
sb.Append(@"%" + Convert.ToString(byStr[i], 16));
}
return (sb.ToString());
}
/// <summary>
/// GB2312解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DeGB2312(string str)
{
byte[] bytes = new byte[str.Split('%').Length ];
int i=0;
foreach (var item in str.Split('%'))
{
if (item !="")
{
//转换为16进制的字节
bytes[i] = Convert.ToByte(item,16);
i++;
}

}
//GB2312的解码
return Encoding.GetEncoding ("GB2312").GetString(bytes);
}

/// <summary>
/// UTF8编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string EnUTF8(string str)
{
StringBuilder sb = new StringBuilder();
byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str);
for (int i = 0; i < byStr.Length; i++)
{
sb.Append(@"%" + Convert.ToString(byStr[i], 16));
}

return (sb.ToString());
}
/// <summary>
/// UTF8解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DeUTF8(string str)
{
byte[] bytes = new byte[str.Split('%').Length ];
int i=0;
foreach (var item in str.Split('%'))
{
if (item !="")
{
bytes[i] = Convert.ToByte(item,16);
i++;
}

}
return Encoding.UTF8.GetString(bytes);
}
}
本站导航
相关文章
柯乐义 Copyright© keleyi.com