in C++ (on Linux with gcc) I'd like to put a byte array (vector<unsigned char>
) to a ostringstream
or a string
.
I know that I can use sprintf
but it doesn't seem to be the best way to use char*
also.
btw: this link did not help
Edit: All answer work so far. But I did not meantion, that I'd like to convert the bytes/hex-values into their string representation, e.g., vector<..> = {0,1,2} -> string = "000102"
. Sorry for that missing but important detail
Little chance of getting an up-vote, but since it is exactly what the OP asked for, and no other answer, including the selected one, oddly, does so:
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
// used by bin2hex for conversion via stream.
struct bin2hex_str
{
std::ostream& os;
bin2hex_str(std::ostream& os) : os(os) {}
void operator ()(unsigned char ch)
{
os << std::hex
<< std::setw(2)
<< static_cast<int>(ch);
}
};
// convert a vector of unsigned char to a hex string
std::string bin2hex(const std::vector<unsigned char>& bin)
{
std::ostringstream oss;
oss << std::setfill('0');
std::for_each(bin.begin(), bin.end(), bin2hex_str(oss));
return oss.str();
}
// or for those who wish for a C++11-compliant version
std::string bin2hex11(const std::vector<unsigned char>& bin)
{
std::ostringstream oss;
oss << std::setfill('0');
std::for_each(bin.begin(), bin.end(),
[&oss](unsigned char ch)
{
oss << std::hex
<< std::setw(2)
<< static_cast<int>(ch);
});
return oss.str();
}
Alternate Stream Dump
If all you want to do is dump an unsigned char fixed array the following will handily do so, which almost no overhead at all.
template<size_t N>
std::ostream& operator <<(std::ostream& os, const unsigned char (&ar)[N])
{
static const char alpha[] = "0123456789ABCDEF";
for (size_t i=0;i<N;++i)
{
os.put(alpha[ (ar[i]>>4) & 0xF ]);
os.put(alpha[ ar[i] & 0xF ]);
}
return os;
}
I use this all the time when I want to dump fixed buffers to an ostream derivitive. The call is dead-simple:
unsigned char data[64];
...fill data[] with, well.. data...
cout << data << endl;
From vector char arr to stl string:
std::string str(v.begin(), v.end());
From stl string to vector char array:
std::string str = "Hellow World!";
std::vector<unsigned char> v(str.begin(), str.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With