首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

識別無 BOM 的 UTF-8 檔案:位元組序列分析法

     編輯:關於ASP.NET

有 BOM 的 UTF-8 易識別,無 BOM 需依編碼規則判斷。UTF-8 編碼規則:

Unicode 範圍UTF-8 位元組模式
000000-00007F0xxxxxxx
000080-0007FF110xxxxx 10xxxxxx
000800-00FFFF1110xxxx 10xxxxxx 10xxxxxx
010000-10FFFF11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

特徵:多位元組字元首位元組有連續 1 後接 0,續位元組固定 10xxxxxx。

判斷演算法

public bool IsUTF8Bytes(byte[] data)
{
    int charByteCounter = 1;
    for (int i = 0; i < data.Length; i++)
    {
        byte curByte = data[i];
        if (charByteCounter == 1)
        {
            if (curByte >= 0x80)
            {
                while (((curByte <<= 1) & 0x80) != 0) charByteCounter++;
                if (charByteCounter == 1 || charByteCounter > 6) return false;
            }
        }
        else
        {
            if ((curByte & 0xC0) != 0x80) return false;
            charByteCounter--;
        }
    }
    if (charByteCounter > 1) throw new Exception("非預期的位元組格式");
    return true;
}

注意:某些特殊字元(如微軟屏蔽聯通傳說中的案例)可能誤判。參考:UTF-8 基礎知識。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved