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());
For setw include:
#include <iomanip>
This should put 01 in stream:
std::ostringstream oss;
unsigned char byte = 0x01;
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte);
Use boost::alogorithm::hex
std::vector<unsigned char> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
For std::ostream
std::ostream ss;
boost::algorithm::hex(v.begin(), v.end(), std::ostream_iterator<char>(ss));
For std::string
std::string res;
boost::algorithm::hex(v.begin(), v.end(), back_inserter(res));
So you want to put the data of a vector of chars into a string? Easy:
string str;
str.resize(vec.size());
for (int n=0;n<vec.size();n++) {
str[n] = vec[n];
}
精彩评论