转换字节数组十六进制字符串
问题描述:
这里是我写的打印的字节数组到十六进制字符串,但现在我想将其保存为的std :: string,并在以后使用它转换字节数组十六进制字符串
这里是我的代码
typedef std::vector<unsigned char> bytes;
void printBytes(const bytes &in)
{
std::vector<unsigned char>::const_iterator from = in.begin();
std::vector<unsigned char>::const_iterator to = in.end();
for (; from != to; ++from) printf("%02X", *from);
}
我该怎么办?我想将它保存为字符串而不是在控制台窗口中打印(显示)? 任何想法!
答
typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes &in)
{
bytes::const_iterator from = in.cbegin();
bytes::const_iterator to = in.cend();
std::ostringstream oss;
for (; from != to; ++from)
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);
return oss.str();
}
“* C++中有像StringBuilder的*无功能” - 是的,有。它被称为'std :: ostringstream'。 –