I coded the following function to convert a std::vector
of uint8_t
to an ascii hexadecimal string
(gnu++98 standard).
...
string uint8_vector_to_hex_string(const vector<uint8_t>& v) {
stringstream ss;
vector<uint8_t>::const_iterator it;
for (it = v.begin(); it != v.end(); it++) {
char hex_char[2];
sprintf(hex_char, "%x", *it);
ss << "\\x" << hex_char;
}
return ss.str();
}
...
It works fine. I was wondering if there is a better way to do this transformation, maybe using not both the stringstream
object and the sprintf
function. Any suggestion?
(Note: The answer is for standard C++; minor modifications regarding range iteration may be needed to work in older dialects. I consider those immaterial to the core problem of algorithmic efficiency that's salient to the question.)
You can save yourself a ton of work by realizing that you basically know the answer in advance and don't need to do all this dynamic work.
In the spirit of "recognizing the algorithm", here's a separated algorithm for place-value formatting of numeric sequences. First the use case:
Now the algorithm:
You could use the stringstream directly to do hex formatting:
If you don't mind using Boost in your project you can use boost::hex