encoding.cpp 1.5 KB

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