日期:2014-05-16 浏览次数:21068 次
在项目开发中不少朋友都会遇到字符串编码、解码或者编码转换的问题。
为了方便初学者朋友,我就在这里抛砖引玉地讲解一下吧。
在C#中我们一般使用System.Text.Encoding来处理字符串编码的问题。
string sources = "C#是一门很优雅的语言";
string code = "00430023662f4e0095e85f884f1896c576848bed8a00";
foreach (var encoding in Encoding.GetEncodings())
{
string temp_code = string.Concat(encoding.GetEncoding().GetBytes(sources).Select(item => item.ToString("x").PadLeft(2, '0')));
if (temp_code == code)
{
Console.WriteLine(temp_code);
Console.WriteLine(encoding.Name);
}
}
string code = "00430023662f4e0095e85f884f1896c576848bed8a00";
byte[] buffer = Regex.Matches(code, "[0-9a-fA-F]{2}").Cast<Match>().Select(item => Convert.ToByte(item.Value, 16)).ToArray();
Console.WriteLine(Encoding.BigEndianUnicode.GetString(buffer));string temp_code = string.Concat(encoding.GetEncoding().GetBytes(sources).Select(item => item.ToString("x").PadLeft(2, '0')));我们上面的解码过程中就是把字符串用各种编码方式进行编码然后和已有的编码比较。 byte[] buffer = Encoding.UTF8.GetBytes(sources);//可能是从其他地方获取过来的参数
buffer = Encoding.Convert(Encoding.UTF8/*原始编码*/, Encoding.ASCII/*目标编码*/, buffer);