Мало шансов получить повышающий голос, но, поскольку именно ОП точно запрашивает ОП, и никакой другой ответ, включая выбранный, как ни странно, не делает:
#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();
}
Дамп альтернативного потока
Если все, что вы хотите сделать, это выгрузить массив без знака char, то следующее handly сделает это, что почти не потребует дополнительных затрат.
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;