For example, using only standard C++03:
#include <cstdlib>
#include <string>
#include <iostream>
int main() {
char const* code = "3D";
std::string str(1, static_cast<char>(std::strtoul(code, 0, 16)));
std::cout << str << std::endl;
}
In a real application, you'd have to test whether the entire string has been converted (second argument to strtoul
) and whether the conversion result is in the allowed range.
Here is a more elaborate example, using C++11 and Boost:
#include <string>
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <boost/numeric/conversion/cast.hpp>
template<typename T>
T parse_int(const std::string& str, int base) {
std::size_t index = 0;
unsigned long result = std::stoul(str, &index, base);
if (index != str.length()) throw std::invalid_argument("Invalid argument");
return boost::numeric_cast<T>(result);
}
int main() {
char const* code = "3D";
std::string str(1, parse_int<char>(code, 16));
std::cout << str << std::endl;
}