获得投票的机会很小,但由于这正是OP 所要求的,而且奇怪的是,没有其他答案,包括选定的答案,这样做:
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
// used by bin2hex for conversion via stream.
struct bin2hex_str
{
std::ostream& os;
bin2hex_str(std::ostream& os) : os(os) {}
void operator ()(unsigned char ch)
{
os << std::hex
<< std::setw(2)
<< static_cast<int>(ch);
}
};
// convert a vector of unsigned char to a hex string
std::string bin2hex(const std::vector<unsigned char>& bin)
{
std::ostringstream oss;
oss << std::setfill('0');
std::for_each(bin.begin(), bin.end(), bin2hex_str(oss));
return oss.str();
}
// or for those who wish for a C++11-compliant version
std::string bin2hex11(const std::vector<unsigned char>& bin)
{
std::ostringstream oss;
oss << std::setfill('0');
std::for_each(bin.begin(), bin.end(),
[&oss](unsigned char ch)
{
oss << std::hex
<< std::setw(2)
<< static_cast<int>(ch);
});
return oss.str();
}
备用流转储
如果您想要做的只是转储一个 unsigned char 固定数组,则以下操作将轻松完成,这几乎没有任何开销。
template<size_t N>
std::ostream& operator <<(std::ostream& os, const unsigned char (&ar)[N])
{
static const char alpha[] = "0123456789ABCDEF";
for (size_t i=0;i<N;++i)
{
os.put(alpha[ (ar[i]>>4) & 0xF ]);
os.put(alpha[ ar[i] & 0xF ]);
}
return os;
}
当我想将固定缓冲区转储到 ostream 派生时,我一直使用它。调用非常简单:
unsigned char data[64];
...fill data[] with, well.. data...
cout << data << endl;