我正在尝试将 BYTES(或无符号字符)的 std::vector 转换为 std::string。 我遇到的问题是,当向量的第一个元素是 0 时,转换后会返回一个空字符串。
我尝试过以下2种方法。 string1 和 string2 都返回空字符串。 我期望的结果是一个以 2 x 0 开头,后跟几个其他字符的字符串。
// vector of BYTE, contains these 7 elements for example: (0,30,85,160,155,93,0)
std::vector<BYTE> data;
// method 1
BYTE* pByteArray = &data[0];
std::string string1 = reinterpret_cast<LPCSTR>(pByteArray);
// method 2
std::string string2(data.begin(),data.end());
// both string1 and string2 return ""
我猜测是因为向量中的第一个字节是 0,所以字符串赋值认为它是 null 或空。 我可以做一些其他转换来返回字符串的其余部分吗?
非常感谢任何帮助。
第二个并不是真的空,请考虑:
// vector of BYTE, contains these 7 elements for example: (0,30,85,160,155,93,0)
std::vector<BYTE> data = {0, 35, 35 ,38};
// method 2
std::string string2(data.begin(),data.end());
cout<< (string2.data()+1) << " size:"<< string2.size() << endl;
/* Notice that size is 4 */
编辑 检查尺寸更加简单,因为它是 4。
关于
data
和 null
终止,作为 docs 请解释(强调我的):
返回的数组以null结尾,即data()和c_str()执行相同的功能。如果empty()返回true,则指针指向 到单个空字符。 (自 C++11 起)
“c++98 安全”方式可能看起来像:
cout.write(string2.data()+1, string2.size()-1);
无论如何,打印只是为了演示字符串“非空”:)
另外,关于第一种方法,您想要:
std::vector<BYTE> data;
//some code
std::string string1(reinterpret_cast<const char *>(&data[0]), data.size());
0x90 0xBA 0xFF
这样的十六进制输出,那么这是我用来生成它们的代码:
template <typename T>
std::string to_hex(T data)
{
std::ostringstream result;
result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << static_cast<int>(data);
return result.str();
}
std::string dump(const std::vector<unsigned char>& data)
{
if (data.empty()) return "";
auto size = data.size();
std::ostringstream result;
for(u32 i =0; i < size; i++)
{
result << "0x" + to_hex(data[i]);
if (i != size)
result << " ";
}
return result.str();
}