diff --git a/components/string_utils.cpp b/components/string_utils.cpp new file mode 100644 index 0000000..740cc1c --- /dev/null +++ b/components/string_utils.cpp @@ -0,0 +1,64 @@ +#include "string_utils.hpp" + +#include +#include + +using namespace iflytop; +/******************************************************************************* + * TOOLS * + *******************************************************************************/ +uint8_t *StringUtils::hex_str_to_bytes(char *data, int32_t len, int32_t &bytelen) { + /** + * @brief + * data: + * 12 34 56 78 90 ab cd ef + * + */ + static uint8_t bytes_cache[1024] = {0}; + static uint8_t data_cache[1024] = {0}; + + int32_t data_len = 0; + + memset(bytes_cache, 0, sizeof(bytes_cache)); + memset(data_cache, 0, sizeof(data_cache)); + + for (int32_t i = 0; i < len; i++) { + if (data[i] == ' ') continue; + if (data[i] == '\r' || data[i] == '\n' || data[i] == '\0') break; + data_cache[data_len] = data[i]; + data_len++; + } + + if (data_len % 2 != 0) { + return NULL; + } + + for (int32_t i = 0; i < data_len; i += 2) { + char c1 = data_cache[i]; + char c2 = data_cache[i + 1]; + if (c1 >= '0' && c1 <= '9') { + c1 = c1 - '0'; + } else if (c1 >= 'a' && c1 <= 'f') { + c1 = c1 - 'a' + 10; + } else if (c1 >= 'A' && c1 <= 'F') { + c1 = c1 - 'A' + 10; + } else { + return NULL; + } + + if (c2 >= '0' && c2 <= '9') { + c2 = c2 - '0'; + } else if (c2 >= 'a' && c2 <= 'f') { + c2 = c2 - 'a' + 10; + } else if (c2 >= 'A' && c2 <= 'F') { + c2 = c2 - 'A' + 10; + } else { + return NULL; + } + + bytes_cache[i / 2] = (c1 << 4) | c2; + } + + bytelen = data_len / 2; + return bytes_cache; +} \ No newline at end of file diff --git a/components/string_utils.hpp b/components/string_utils.hpp new file mode 100644 index 0000000..dd4249d --- /dev/null +++ b/components/string_utils.hpp @@ -0,0 +1,13 @@ +#pragma once +#include +namespace iflytop { +using namespace std; +class StringUtils { + private: + /* data */ + public: + StringUtils(/* args */){}; + ~StringUtils(){}; + static uint8_t *hex_str_to_bytes(char *data, int32_t len, int32_t &bytelen); +}; +} // namespace iflytop