Skip to content

Instantly share code, notes, and snippets.

@adler3d
Created March 11, 2018 11:51
Show Gist options
  • Save adler3d/34fe0f527ab67081596d55db4db4281e to your computer and use it in GitHub Desktop.
Save adler3d/34fe0f527ab67081596d55db4db4281e to your computer and use it in GitHub Desktop.
"string to hex" and "hex to string"
#include <string>
using std::string;
inline string to_hex(unsigned char v){
char buf[3]={0,0,0};
sprintf(buf,"%02x",v);
return buf;
}
inline char from_hex(char c1,char c2){
char buf[3]={c1,c2,0};
size_t v;
sscanf(buf,"%02x",&v);
return (char&)v;
}
inline string str2hex(const string&s)
{
string out;
out.reserve(s.size()*2);
for(size_t i=0;i<s.size();i++)out+=to_hex((unsigned char&)s[i]);
return out;
}
inline string hex2str(const string&s){
string out;
out.reserve(s.size()/2);
for(size_t i=0;i<s.size();i+=2){
out.push_back(from_hex(s[i],s[i+1]));
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment