First of all, you are using an unhealthy mix of C and C++; try to choose one or the other and stick to it (that is, use its idioms). Your code has a memory leak, unnecessary copies, etc...
Second, you just need two things:
- A way to convert two consecutive characters (hexadecimal digits) into their numeric counterpart (as a
char
I guess ?) - A way to store the successive conversions
For the first, whilst indeed you could sscanf
, C++ tends to lean toward using istream
instead though here it's tricky because of the absence of "stops"; so we can just do it manually:
char fromHexadecimal(char const digit) {
if ('0' <= digit and digit <= '9') { return digit - '0'; }
if ('a' <= digit and digit <= 'f') { return 10 + digit - 'a'; }
if ('A' <= digit and digit <= 'F') { return 10 + digit - 'A'; }
throw std::runtime_error("Unknown hexadecimal digit");
}
char fromHexadecimal(char digit0, char digit1) {
return fromHexadecimal(digit0) * 16 + fromHexadecimal(digit1);
}
With that hurdle out of the way, we can just use strings both for input and output; after all a string
is just a collection of char
:
std::string fromHexadecimal(std::string const& hex) {
if (hex.size() % 2 != 0) {
throw std::runtime_error("Requires an even number of hex digits");
}
std::string result;
for (size_t i = 0, max = hex.size() / 2; i != max; ++i) {
result.push_back(fromHexadecimal(hex.at(2*i), hex.at(2*i+1)));
}
return result;
}