Skip to content

Instantly share code, notes, and snippets.

@evakili
Created December 18, 2017 12:03
Show Gist options
  • Save evakili/746bbe3ece8b800031574c6465ef1570 to your computer and use it in GitHub Desktop.
Save evakili/746bbe3ece8b800031574c6465ef1570 to your computer and use it in GitHub Desktop.
Converting a stream of bytes to a string of hex with C++
#include <iostream>
#include <sstream>
#include <iomanip>
#include <iterator>
template<typename T, int Width>
struct fixed_width_t
{
fixed_width_t(T val) : val{ val } {}
T val;
};
template <typename CharT, typename T, int Width>
auto& operator<<(std::basic_ostream<CharT>& out, const fixed_width_t<T, Width> &fixed_width_val)
{
return out << std::setw(Width) << fixed_width_val.val;
}
template<typename CharT>
auto HexPrinter(std::basic_ostream<CharT>& stream)
{
stream << std::hex << std::setfill(stream.widen('0'));
return std::ostream_iterator<fixed_width_t<int, 2>, CharT>(stream);
}
template<typename CharT, typename Cont>
auto ByteStreamToHexString(const Cont& buffer)
{
std::basic_ostringstream<CharT> result{};
std::copy(std::begin(buffer), std::end(buffer), HexPrinter(result));
return result.str();
}
#include <vector>
int main(int argc, char* argv[])
{
std::cout << ByteStreamToHexString<char>(std::vector<char>(16, 0)) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment