You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6 KiB

2 years ago
  1. #include "string_utils.hpp"
  2. #include <stdint.h>
  3. #include <string.h>
  4. using namespace iflytop;
  5. /*******************************************************************************
  6. * TOOLS *
  7. *******************************************************************************/
  8. uint8_t *StringUtils::hex_str_to_bytes(char *data, int32_t len, int32_t &bytelen) {
  9. /**
  10. * @brief
  11. * data:
  12. * 12 34 56 78 90 ab cd ef
  13. *
  14. */
  15. static uint8_t bytes_cache[1024] = {0};
  16. static uint8_t data_cache[1024] = {0};
  17. int32_t data_len = 0;
  18. memset(bytes_cache, 0, sizeof(bytes_cache));
  19. memset(data_cache, 0, sizeof(data_cache));
  20. for (int32_t i = 0; i < len; i++) {
  21. if (data[i] == ' ') continue;
  22. if (data[i] == '\r' || data[i] == '\n' || data[i] == '\0') break;
  23. data_cache[data_len] = data[i];
  24. data_len++;
  25. }
  26. if (data_len % 2 != 0) {
  27. return NULL;
  28. }
  29. for (int32_t i = 0; i < data_len; i += 2) {
  30. char c1 = data_cache[i];
  31. char c2 = data_cache[i + 1];
  32. if (c1 >= '0' && c1 <= '9') {
  33. c1 = c1 - '0';
  34. } else if (c1 >= 'a' && c1 <= 'f') {
  35. c1 = c1 - 'a' + 10;
  36. } else if (c1 >= 'A' && c1 <= 'F') {
  37. c1 = c1 - 'A' + 10;
  38. } else {
  39. return NULL;
  40. }
  41. if (c2 >= '0' && c2 <= '9') {
  42. c2 = c2 - '0';
  43. } else if (c2 >= 'a' && c2 <= 'f') {
  44. c2 = c2 - 'a' + 10;
  45. } else if (c2 >= 'A' && c2 <= 'F') {
  46. c2 = c2 - 'A' + 10;
  47. } else {
  48. return NULL;
  49. }
  50. bytes_cache[i / 2] = (c1 << 4) | c2;
  51. }
  52. bytelen = data_len / 2;
  53. return bytes_cache;
  54. }