Created
April 11, 2019 20:05
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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