Skip to content

Instantly share code, notes, and snippets.

@jrwren
Created April 11, 2019 20:05
Show Gist options
  • Save jrwren/b33ede61b76f164e4a0ecbd1ea1eacd4 to your computer and use it in GitHub Desktop.
Save jrwren/b33ede61b76f164e4a0ecbd1ea1eacd4 to your computer and use it in GitHub Desktop.
all of the answers for using ostream_iterator and copy to turn a string to hex in c++ on Stack Overflow are wrong. This works.
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iomanip>
using namespace std;
template <typename T>
struct hexwrite
{
hexwrite(T v_) : v(v_) {}
T v;
};
template <typename T>
std::ostream& operator<< (std::ostream& ostr, const hexwrite<T> &fwv)
{
return ostr << std::setw(2)<< std::setfill('0')<< std::hex << fwv.v;
}
int main()
{
vector<char> data = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
ostringstream hexout;
copy(data.begin(), data.end(), ostream_iterator< hexwrite<int> >(hexout, " "));
cout << hexout.str() << endl;
hexout.clear();
for(auto d : data)
hexout << d;
cout << hexout.str() << endl;
hexout.clear();
for(auto const &d : data)
hexout << setw(2) << hex << setfill('0') << d;
cout << hexout.str() << endl;
hexout.clear();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment