diff options
author | Klaus Aehlig <klaus.aehlig@huawei.com> | 2022-06-13 13:30:13 +0200 |
---|---|---|
committer | Oliver Reiche <oliver.reiche@huawei.com> | 2022-06-13 13:30:13 +0200 |
commit | f5c12e59e34107f1fc16349d843a8f64d7dd5459 (patch) | |
tree | 498c83488273b45daa2618c27b5a09659ea10da8 /src/utils/cpp | |
parent | d9dfe9d984a5871e15d6f1c7d9d1515925ed7159 (diff) | |
download | justbuild-f5c12e59e34107f1fc16349d843a8f64d7dd5459.tar.gz |
utils: convert hex to string
Diffstat (limited to 'src/utils/cpp')
-rw-r--r-- | src/utils/cpp/hex_string.hpp | 18 |
1 files changed, 18 insertions, 0 deletions
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 <iomanip> +#include <iostream> +#include <optional> #include <sstream> #include <string> @@ -16,4 +18,20 @@ return ss.str(); } +[[nodiscard]] static inline auto FromHexString(std::string const& hexstring) + -> std::optional<std::string> { + 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 |