首页 > 编程技术 > C语言

C语言中判断一个char*是不是utf8编码

发布时间:2020-4-25 17:31

C语言中判断一个char*是不是utf8编码

里我修改了一下, 纯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); 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

标签:[!--infotagslink--]

您可能感兴趣的文章: