您的位置:首页 > 服装鞋帽 > 女装 > 根据字节数组的前四字节判断字符编码

根据字节数组的前四字节判断字符编码

luyued 发布于 2011-01-19 06:16   浏览 N 次  

string filename = "C://TEST.TXT";
string str = "ab中国";

public void test(System.Text.Encoding encod)
{
System.IO.File.AppendAllText(filename, str, encod);

byte[] arrBytes = File.ReadAllBytes(filename);//实际获取中不用传递整个数组,前面4字节即可

System.IO.File.Delete(filename);
txtContent.Text += (encod.ToString()+" >"+encod.WebName + ">>"+ ReturnEncoding(arrBytes).WebName) + System.Environment.NewLine;
}

///
/// 根据字节数组的前四字节判断字符编码
///

///
///
public static System.Text.Encoding ReturnEncoding(byte[] tB)
{

byte tB1 = 0;
byte tB2 = 0;
byte tB3 = 0;
byte tB4 = 0;
if (tB.Length <2)
return null;

tB1 = tB[0];
tB2 = tB[1];
if (tB.Length >= 3) tB3 = tB[2];
if (tB.Length >= 4) tB4 = tB[3];

if ((tB1 == 0xfe &&tB2 == 0xff)) return System.Text.Encoding.BigEndianUnicode;
if ((tB1 == 0xff &&tB2 == 0xfe &&tB3 != 0xff)) return System.Text.Encoding.Unicode;
if ((tB1 == 0xef &&tB2 == 0xbb &&tB3 == 0xbf)) return System.Text.Encoding.UTF8;

return System.Text.Encoding.Default;
}

//
System.Text.ASCIIEncoding >us-ascii >>gb2312
System.Text.UnicodeEncoding >unicodeFFFE >>unicodeFFFE
System.Text.DBCSCodePageEncoding >gb2312 >>gb2312
System.Text.UnicodeEncoding >utf-16 >>utf-16
System.Text.UTF32Encoding >utf-32 >>utf-16
System.Text.UTF7Encoding >utf-7 >>gb2312
System.Text.UTF8Encoding >utf-8 >>utf-8

ab中国

ascii 97 98 63 63 (不能识别'中国')
big 254 2550 97 0 98 78 45 86 253
gb2312 97 98 214 208 185 250 (default)
unicode 255 254 97 0 98 0 45 78 253 86
utf32 255 254 0 0 97 0 0 0 98 0 0 0 45 78 00 253 86 00
utf7 97 98 43 84 105 49 87 47 81 45
utf8 239 187 191 97 98 228 184 173 229 155 189
类别:c# 查看评论
图文资讯
广告赞助商