判断一个char*是不是utf8编码

时间:2023-01-05 09:24:30

原文链接: http://www.cppblog.com/izualzhy/archive/2012/12/03/195933.html


这里我修改了一下, 纯ASCII编码的字符串也返回true, 因为UTF8和ASCII兼容


int utf8_check(const char* str, size_t length) {
size_t i;
int nBytes;
unsigned char chr;

i = 0;
nBytes = 0;
while (i < length) {
chr = *(str + i);

if (nBytes == 0) { //计算字节数
if ((chr & 0x80) != 0) {
while ((chr & 0x80) != 0) {
chr <<= 1;
nBytes++;
}
if ((nBytes < 2) || (nBytes > 6)) {
return 0; //第一个字节最少为110x xxxx
}
nBytes--; //减去自身占的一个字节
}
} else { //多字节除了第一个字节外剩下的字节
if ((chr & 0xC0) != 0x80) {
return 0; //剩下的字节都是10xx xxxx的形式
}
nBytes--;
}
i++;
}
return (nBytes == 0);
}