VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之utf8编码检测方法分享

代码如下:

public bool isUtf8(byte[] rawText)
        {
            bool result = true;

 

            if (rawText == null)
            {
                return !result;
            }

            int pos = 0;
            while (pos < rawText.Length && result)
            {
                if ((rawText[pos] & 0x7F) == rawText[pos])
                {
                    pos++;
                }
                else
                {
                    int bitLen = 7;

                    while (((rawText[pos] >> bitLen) & 0x01) == 1 && bitLen > 0)
                    {
                        bitLen--;
                    }

                    int byteCount = 7 - bitLen;

                    if (byteCount > 1 && byteCount < 7)
                    {
                        for (int i = 1; i < byteCount; ++i)
                        {
                            if (pos + i >= rawText.Length || (rawText[pos + i] & 0xBF) != rawText[pos + i])
                            {
                                result = false;
                                break;
                            }
                        }

                        pos += byteCount;
                    }
                    else
                    {
                        result = false;
                    }
                }
            }

            return result;
        }



相关教程