C# 判断字节(byte[])是否是UTF-8

public static bool IsValidUtf8(byte[] data)
{
    int i = 0;
    while (i < data.Length)
    {
        int byteCount = 0;
        // 检查第一个字节
        if ((data[i] & 0x80) == 0) // 0xxxxxxx
        {
            byteCount = 1;
        }
        else if ((data[i] & 0xE0) == 0xC0) // 110xxxxx
        {
            byteCount = 2;
        }
        else if ((data[i] & 0xF0) == 0xE0) // 1110xxxx
        {
            byteCount = 3;
        }
        else if ((data[i] & 0xF8) == 0xF0) // 11110xxx
        {
            byteCount = 4;
        }
        else
        {
            return false; // 不是有效的UTF-8起始字节
        }

        // 检查后续字节
        for (int j = 1; j < byteCount; j++)
        {
            if ((data[i + j] & 0xC0) != 0x80) // 不是10xxxxxx
            {
                return false;
            }
        }

        i += byteCount;
    }

    return true;
}

本文来自 www.luofenming.com