Last active
September 10, 2020 09:17
-
-
Save uhziel/d7b5240c583dfced62aec9fed2713f10 to your computer and use it in GitHub Desktop.
cpp_hex2bin
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
void Bin2Hex(const char* buf, size_t len, std::string& out) | |
{ | |
std::ostringstream ostr; | |
ostr << std::hex; | |
ostr.fill('0'); | |
for (size_t i = 0; i < len; i++) | |
{ | |
unsigned char tmp = buf[i]; | |
ostr << std::setw(2) << static_cast<short>(tmp); | |
} | |
out = ostr.str(); | |
} | |
void Hex2Bin(const std::string& hex, std::string& out) | |
{ | |
lightAssert(hex.length() % 2 == 0); | |
std::string tmp; | |
tmp.reserve(hex.length() / 2); | |
std::string extract; | |
for (std::string::const_iterator pos = hex.begin(); pos < hex.end(); pos += 2) | |
{ | |
extract.assign(pos, pos + 2); | |
tmp.push_back(strtol(extract.c_str(), NULL, 16)); | |
} | |
out = tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/18906027/missing-punctuation-from-c-hex2bin