賛成票を得る可能性はほとんどありませんが、それはまさに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;