What is the best way to convert a string to hex and vice versa in C++?
Example:
- A string like
"Hello World"to hex format:48656C6C6F20576F726C64 - And from hex
48656C6C6F20576F726C64to string:"Hello World"
What is the best way to convert a string to hex and vice versa in C++?
Example:
"Hello World" to hex format: 48656C6C6F20576F726C6448656C6C6F20576F726C64 to string: "Hello World"As of C++17 there's also std::from_chars. The following function takes a string of hex characters and returns a vector of T:
#include <charconv>
template<typename T>
std::vector<T> hexstr_to_vec(const std::string& str, unsigned char chars_per_num = 2)
{
std::vector<T> out(str.size() / chars_per_num, 0);
T value;
for (std::size_t i = 0; i < str.size() / chars_per_num; i++) {
std::from_chars<T>(
str.data() + (i * chars_per_num),
str.data() + (i * chars_per_num) + chars_per_num,
value,
16
);
out[i] = value;
}
return out;
}
Here is an other solution, largely inspired by the one by @fredoverflow.
/**
* Return hexadecimal representation of the input binary sequence
*/
std::string hexitize(const std::vector<char>& input, const char* const digits = "0123456789ABCDEF")
{
std::ostringstream output;
for (unsigned char gap = 0, beg = input[gap]; gap < input.length(); beg = input[++gap])
output << digits[beg >> 4] << digits[beg & 15];
return output.str();
}
Length was required parameter in the intended usage.
#include "boost/algorithm/hex.hpp"
std::string hexed = boost::algorithm::hex(std::string("input"));
https://www.boost.org/doc/libs/1_78_0/boost/algorithm/hex.hpp