feat: add hex
This commit is contained in:
38
src/hex.cpp
Normal file
38
src/hex.cpp
Normal 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
|
||||
Reference in New Issue
Block a user