Created
March 11, 2018 11:51
-
-
Save adler3d/34fe0f527ab67081596d55db4db4281e to your computer and use it in GitHub Desktop.
"string to hex" and "hex to string"
This file contains hidden or 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 <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