diff --git a/CMakeLists.txt b/CMakeLists.txt index 17a0929..5067630 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,9 @@ cmake_minimum_required(VERSION 3.9 FATAL_ERROR) project(solanaceae) add_library(solanaceae_util + ./solanaceae/util/utils.hpp + ./solanaceae/util/utils.cpp + ./solanaceae/util/config_model.hpp ./solanaceae/util/config_model.inl diff --git a/solanaceae/util/utils.cpp b/solanaceae/util/utils.cpp new file mode 100644 index 0000000..3e1a3d5 --- /dev/null +++ b/solanaceae/util/utils.cpp @@ -0,0 +1,53 @@ +#include "./utils.hpp" + +#include + +namespace detail { + constexpr uint8_t nib_from_hex(char c) { + assert((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')); + + if (c >= '0' && c <= '9') { + return static_cast(c) - '0'; + } else if (c >= 'a' && c <= 'f') { + return (static_cast(c) - 'a') + 10u; + } else { + return 0u; + } + } + + constexpr char nib_to_hex(uint8_t c) { + assert(c <= 0x0f); + + if (c <= 0x09) { + return c + '0'; + } else { + return (c - 10u) + 'a'; + } + } +} // detail + +std::vector hex2bin(const std::string& str) { + return hex2bin(std::string_view{str}); +} + +std::vector hex2bin(const std::string_view str) { + assert(str.size() % 2 == 0); // TODO: should this be a hard assert?? + std::vector bin{}; + bin.resize(str.size()/2, 0); + + for (size_t i = 0; i < bin.size(); i++) { + bin[i] = detail::nib_from_hex(str[i*2]) << 4 | detail::nib_from_hex(str[i*2+1]); + } + + return bin; +} + +std::string bin2hex(const std::vector& data) { + std::string str; + for (size_t i = 0; i < data.size(); i++) { + str.push_back(detail::nib_to_hex(data[i] >> 4)); + str.push_back(detail::nib_to_hex(data[i] & 0x0f)); + } + return str; +} + diff --git a/solanaceae/util/utils.hpp b/solanaceae/util/utils.hpp new file mode 100644 index 0000000..638427c --- /dev/null +++ b/solanaceae/util/utils.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include +#include +#include + +[[nodiscard]] std::vector hex2bin(const std::string& str); +[[nodiscard]] std::vector hex2bin(const std::string_view str); +[[nodiscard]] std::string bin2hex(const std::vector& bin); +