如何在不使用reinterpret_cast的情况下将无符号字符转换为std::string?

发布于 2024-09-01 12:06:45 字数 327 浏览 6 评论 0原文

我有一个 std::string 中需要的无符号字符数组,但我当前的方式使用我想避免的reinterpret_cast。有没有更干净的方法来做到这一点?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

辞慾 2024-09-08 12:06:45

使用迭代器构造函数:

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

假设您希望将无符号字符转换为 char。如果您希望它们被重新解释,那么您应该使用reinterpret_cast。那将是完全干净的,因为你所说的就是所做的。

但在您的示例中,这没有任何区别,因为数组中的所有值都在 0CHAR_MAX 范围内。因此,可以保证这些值在 char 中的表示方式与在 unsigned char 中的表示方式相同,因此重新解释它们与转换它们是相同的。如果您的值大于 CHAR_MAX,则允许实现以不同方式对待它们。

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.

梦醒时光 2024-09-08 12:06:45

你尝试过流吗?

     stringstream s;
     s << my_txt;

     string str_my_txt = s.str();

Have you tried sstream?

     stringstream s;
     s << my_txt;

     string str_my_txt = s.str();
梦初启 2024-09-08 12:06:45
  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;
   }
  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;
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文