在 C++ 中将 uint8_t* 转换为 std::string?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4508911/
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
Convert uint8_t* to std::string in C++?
提问by Lincoln
Possible Duplicate:
How to Convert Byte* to std::string in C++?
I'm on an embedded device and try to receive a message.
This message is given by a const uint8_t* data
and its length size_t len
.
我在嵌入式设备上并尝试接收消息。此消息由 aconst uint8_t* data
及其长度给出size_t len
。
Now I need a std::string
to output my data.
现在我需要一个std::string
来输出我的数据。
回答by sbi
If you don't want to convert the encoding, this will work:
如果您不想转换编码,这将起作用:
std::string s( data, data+len );
If you want to convert UTF-8 into whatever system encoding is used by your platform, you need to use some platform-specific means.
如果您想将 UTF-8 转换为您的平台使用的任何系统编码,您需要使用一些特定于平台的方法。
回答by Oliver Charlesworth
Is your uint8*
string null-terminated? If so, you can just do:
您的uint8*
字符串是否以空字符结尾?如果是这样,你可以这样做:
std::string mystring(data);
回答by Flinsch
For some case sizeof(uint8) != sizeof(char), you could do:
对于某些情况 sizeof(uint8) != sizeof(char),你可以这样做:
std::string output( len, 0 );
for ( size_t i = 0; i < len; ++i )
output[ i ] = static_cast<char>( data[ i ] );