views:

116

answers:

3

Hi,

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

+1  A: 

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];
}
Alexander Rafferty
why are you using stl string without utilizing other stl features? (for_each, iterator, etc)
YeenFei
+6  A: 

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());
wengseng
Are you talking about this? for(int i=0; i<v.size(); i++) { str+= v[i]; }
wengseng
As YeenFei pointed out, if you want a leading zero, probably you can use sprintf...
wengseng
+2  A: 

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);
xoride