feat: add hex

This commit is contained in:
2026-01-29 23:22:17 +01:00
parent 110d1df50d
commit f49802a1a6
4 changed files with 179 additions and 0 deletions

38
src/hex.cpp Normal file
View File

@@ -0,0 +1,38 @@
#include <cpputils/hex.h>
#include <iomanip>
#include <ios>
#include <string>
namespace cpputils {
namespace hex {
std::string toHex(std::string const& input) {
std::stringstream ss;
for (auto c : input) {
ss << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<unsigned int>(static_cast<unsigned char>(c));
}
return ss.str();
}
std::string fromHex(std::string const& input) {
if (input.size() % 2 != 0) {
return {};
}
std::string out;
out.reserve(input.size() / 2);
for (size_t i = 0; i < input.size(); i += 2) {
int hi = hexVal(input[i]);
int lo = hexVal(input[i + 1]);
if (hi < 0 || lo < 0) {
return {};
}
out.push_back(static_cast<char>((hi << 4) | lo));
}
return out;
}
} // namespace hex
} // namespace cpputils