且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C++ 中将 unsigned char* 转换为 std::string?

更新时间:2022-02-05 05:46:59

您只需要将 unsigned char 转换为 char 作为 string 类没有接受 unsigned char 的构造函数:

You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;

但是,如果您的字节数组包含空值,您将需要在构造函数中使用长度参数,如果您不包含,则只有部分数组会以字符串结尾(数组直到第一个空值)

However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;