开发者

Way to get unsigned char into a std::string without reinterpret_cast?

开发者 https://www.devze.com 2022-12-31 10:15 出处:网络
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?

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, 0x开发者_如何学Python73, 0x72, 0x55
}
unsigned int my_txt_len = 12;

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


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, because all of the values in your array are within the range 0 to CHAR_MAX. So it's guaranteed that those values are represented the same way in char as they are in unsigned char, and hence that reinterpreting them is the same as converting them. If you had values greater then CHAR_MAX then implementations are allowed to treat them differently.


Have you tried sstream?

     stringstream s;
     s << my_txt;

     string str_my_txt = s.str();


  int _tmain(int argc, _TCHAR* argv[])
  {
        unsigned char temp  = 200;
        char temp1[4];

        sprintf(temp1, "%d", temp);

        std::string strtemp(temp1);

        std::cout<<strtemp.c_str()<<std::endl;

        return 0;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消