有 BOM 的 UTF-8 易識別,無 BOM 需依編碼規則判斷。UTF-8 編碼規則:
| Unicode 範圍 | UTF-8 位元組模式 |
|---|---|
| 000000-00007F | 0xxxxxxx |
| 000080-0007FF | 110xxxxx 10xxxxxx |
| 000800-00FFFF | 1110xxxx 10xxxxxx 10xxxxxx |
| 010000-10FFFF | 11110xxx 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 基礎知識。