views:

181

answers:

2

I have an unsigned char array that I need in a std::string, but my current way uses reinterpret_cast which I would like to avoid. Is there a cleaner way to do this?

unsigned char my_txt[] = {
  0x52, 0x5f, 0x73, 0x68, 0x7e, 0x29, 0x33, 0x74, 0x74, 0x73, 0x72, 0x55
}
unsigned int my_txt_len = 12;

std::string my_std_string(reinterpret_cast<const char *>(my_txt), my_txt_len);
A: 

Have you tried sstream?

     stringstream s;
     s << my_txt;

     string str_my_txt = s.str();
David Relihan
It worked great for me, not sure why you say it does not work?
WilliamKF
Yep - your quite right!!! Had a momentery lapse of reason there!!!
David Relihan
Turns out I was just getting lucky, the missing terminating NULL causes ABR in some cases. See related question here: http://stackoverflow.com/questions/2889074/why-do-i-get-this-strange-output-behavior
WilliamKF
+2  A: 

Use the iterator constructor:

std::string my_std_string(my_txt, my_txt + my_txt_len);

This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done. In your example, though, it doesn't make any difference.

Steve Jessop