如何在不使用reinterpret_cast的情况下将无符号字符转换为std::string?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用迭代器构造函数:
假设您希望将无符号字符转换为 char。如果您希望它们被重新解释,那么您应该使用
reinterpret_cast
。那将是完全干净的,因为你所说的就是所做的。但在您的示例中,这没有任何区别,因为数组中的所有值都在
0
到CHAR_MAX
范围内。因此,可以保证这些值在char
中的表示方式与在unsigned char
中的表示方式相同,因此重新解释它们与转换它们是相同的。如果您的值大于CHAR_MAX
,则允许实现以不同方式对待它们。Use the iterator constructor:
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
toCHAR_MAX
. So it's guaranteed that those values are represented the same way inchar
as they are inunsigned char
, and hence that reinterpreting them is the same as converting them. If you had values greater thenCHAR_MAX
then implementations are allowed to treat them differently.你尝试过流吗?
Have you tried sstream?