Skip to content

Instantly share code, notes, and snippets.

@uhziel
Last active September 10, 2020 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhziel/d7b5240c583dfced62aec9fed2713f10 to your computer and use it in GitHub Desktop.
Save uhziel/d7b5240c583dfced62aec9fed2713f10 to your computer and use it in GitHub Desktop.
cpp_hex2bin
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