判断字符串是否是utf-8编码格式[C/C++]

/*************************************************************
 * 校验字符串是否以UTF-8编码,主要原理是判断位数是否对应
 * UTF-8编码规则:
 * 1字节 0xxxxxxx 注:和ascii码相同,这种不用判断,直接跳过
 * 2字节 110xxxxx 10xxxxxx 
 * 3字节 1110xxxx 10xxxxxx 10xxxxxx 
 * 4字节 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 
 * 5字节 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 
 * 6字节 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 
 * 返回值 :0是utf8  其他不是utf8
 * ************************************************************/
INT32 Is_Utf8_String(UINT8 *utf,UINT32 length)
{
    UINT32 check_sub    = 0;
    UINT32 i            = 0;
    UINT32 j            = 0;

    for (i = 0; i < length; i++)
    {
        if (check_sub == 0)
        {
            if ((utf[i] >> 7) == 0) //0xxx xxxx
            {
                continue;
            }

            /* 获取单个 utf8 除了头部所占用字节个数 */
            struct
            {
                UINT8 cal;
                UINT8 cmp;
            } Utf8NumMap[] = {
                {0xE0,      0xC0},      //110xxxxx
                {0xF0,      0xE0},      //1110xxxx
                {0xF8,      0xF0},      //11110xxx
                {0xFC,      0xF8},      //111110xx
                {0xFE,      0xFC},      //1111110x
            };
            for (j = 0; j < (sizeof(Utf8NumMap)/sizeof(Utf8NumMap[0])); j++)
            {
                if ((utf[i] & Utf8NumMap[j].cal) == Utf8NumMap[j].cmp)
                {
                    //printf("%u:%u:%x\n", __LINE__, i, utf[i]);
                    check_sub = j + 1;
                    break;
                }
            }
            if(0 == check_sub)
            {
                return 1;
            }
        }
        else
        {
            /* 校验字节是否合法 */
            if ((utf[i] & 0xC0) != 0x80)
            {
                return 2;
            }
            check_sub--;
        }
    }
    return 0;
}

 

参考转载于:https://blog.csdn.net/weixin_30824277/article/details/96259908

你可能感兴趣的:(c/c++)