C#简单判断字符编码的方法

时间:2022-04-23 20:17:54

本文实例讲述了C#简单判断字符编码的方法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public static string GetText(byte[] buff)
{
  string strReslut = string.Empty;
  if (buff.Length > 3)
  {
    if (buff[0] == 239 && buff[1] == 187 && buff[2] == 191)
    {// utf-8
      strReslut = Encoding.UTF8.GetString(buff);
    }
    else if (buff[0] == 254 && buff[1] == 255)
    {// big endian unicode
      strReslut = Encoding.BigEndianUnicode.GetString(buff);
    }
    else if (buff[0] == 255 && buff[1] == 254)
    {// unicode
      strReslut = Encoding.Unicode.GetString(buff);
    }
    else if (isUtf8(buff))
    {// utf-8
      strReslut = Encoding.UTF8.GetString(buff);
    }
    else
    {// ansi
      strReslut = Encoding.Default.GetString(buff);
    }
  }
  return strReslut;
}
// 110XXXXX, 10XXXXXX
// 1110XXXX, 10XXXXXX, 10XXXXXX
// 11110XXX, 10XXXXXX, 10XXXXXX, 10XXXXXX
private static bool isUtf8(byte[] buff)
{
  for (int i = 0; i < buff.Length; i++)
  {
    if ((buff[i] & 0xE0) == 0xC0) // 110x xxxx 10xx xxxx
    {
      if ((buff[i + 1] & 0x80) != 0x80)
      {
        return false;
      }
    }
    else if ((buff[i] & 0xF0) == 0xE0) // 1110 xxxx 10xx xxxx 10xx xxxx
    {
      if ((buff[i + 1] & 0x80) != 0x80 || (buff[i + 2] & 0x80) != 0x80)
      {
        return false;
      }
    }
    else if ((buff[i] & 0xF8) == 0xF0) // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
    {
      if ((buff[i + 1] & 0x80) != 0x80 || (buff[i + 2] & 0x80) != 0x80 || (buff[i + 3] & 0x80) != 0x80)
      {
        return false;
      }
    }
  }
  return true;
}
// news.sohu.com
private static bool isGBK(byte[] buff)
{
  return false;
}

希望本文所述对大家C#程序设计有所帮助。