C++ 在不重新解释转换的情况下将无符号字符转换为 std::string 的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2840835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Way to get unsigned char into a std::string without reinterpret_cast?
提问by WilliamKF
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?
我在 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);
回答by Steve Jessop
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 wantthem to be reinterpreted, then you should use reinterpret_cast
. That would be perfectly clean, since what you say is exactly what is done.
这是假设您希望将无符号字符转换为字符。如果您希望重新解释它们,那么您应该使用reinterpret_cast
. 那将是完全干净的,因为您所说的正是所做的。
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.
但是,在您的示例中,它没有任何区别,因为数组中的所有值都在0
to范围内CHAR_MAX
。因此可以保证这些值的表示方式char
与它们在中的表示方式相同unsigned char
,因此重新解释它们与转换它们是相同的。如果您有更大的值,则CHAR_MAX
允许实现以不同的方式对待它们。
回答by Robben_Ford_Fan_boy
Have you tried sstream?
你试过 sstream 吗?
stringstream s;
s << my_txt;
string str_my_txt = s.str();
回答by Praveer Kumar
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;
}