encoding.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #include "tool-type.h"
  2. #include "encoding.h"
  3. namespace aFuntool {
  4. /**
  5. * 检查给定字符串是否utf-8编码
  6. * @param str 字符串
  7. */
  8. bool isCharUTF8(const char *str) {
  9. int code = 0; // utf-8 多字节数
  10. for (const char *ch = str; *ch != NUL; ch++) {
  11. unsigned char c = *ch;
  12. unsigned char c_ = ~c;
  13. assertFatalErrorLog(code >= 0 && code <= 5, aFunSysLogger, 2, "str = %s", str);
  14. if (code == 0) {
  15. if ((c_ & 0xFC) == 0 && (c & 0x02) == 0) // 检查是否为1111110x, 先对其取反, 使用0xFC掩码检查前6位是否为0, 然后单独检查倒数第二位是否为0
  16. code = 5; // 剩余 5 个字节
  17. else if ((c_ & 0xF8) == 0 && (c & 0x04) == 0)
  18. code = 4; // 剩余 4 个字节
  19. else if ((c_ & 0xF0) == 0 && (c & 0x08) == 0)
  20. code = 3; // 剩余 3 个字节
  21. else if ((c_ & 0xE0) == 0 && (c & 0x10) == 0)
  22. code = 2; // 剩余 2 个字节
  23. else if ((c_ & 0xC0) == 0 && (c & 0x20) == 0)
  24. code = 1; // 剩余 1 个字节
  25. else if ((c & 0x80) == 0) // 检查最高位是否为0
  26. code = 0;
  27. else
  28. return false;
  29. } else if ((c_ & 0x80) == 0 && (c & 0x40) == 0)
  30. code--;
  31. else
  32. return false;
  33. }
  34. return true;
  35. }
  36. }