From f5c12e59e34107f1fc16349d843a8f64d7dd5459 Mon Sep 17 00:00:00 2001 From: Klaus Aehlig Date: Mon, 13 Jun 2022 13:30:13 +0200 Subject: utils: convert hex to string --- src/utils/cpp/hex_string.hpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/utils/cpp/hex_string.hpp') diff --git a/src/utils/cpp/hex_string.hpp b/src/utils/cpp/hex_string.hpp index 86ea1b9e..b46240f8 100644 --- a/src/utils/cpp/hex_string.hpp +++ b/src/utils/cpp/hex_string.hpp @@ -2,6 +2,8 @@ #define INCLUDED_SRC_UTILS_CPP_HEX_STRING_HPP #include +#include +#include #include #include @@ -16,4 +18,20 @@ return ss.str(); } +[[nodiscard]] static inline auto FromHexString(std::string const& hexstring) + -> std::optional { + try { + const size_t kHexBase = 16; + std::stringstream ss{}; + for (size_t i = 0; i < hexstring.length(); i += 2) { + unsigned char c = + std::stoul(hexstring.substr(i, 2), nullptr, kHexBase); + ss << c; + } + return ss.str(); + } catch (...) { + return std::nullopt; + } +} + #endif // INCLUDED_SRC_UTILS_CPP_HEX_STRING_HPP -- cgit v1.2.3