2

I am looking for a C++ library function or built-in function that can read a long hexadecimal string (ex. SHA256 hash) and turn that into an unsigned char array. I tried using stringstream for this but to no avail.

For example -

bool StringToHex(std::string inStr, unsigned char *outStr);

Input - inStr = "5a12b43d3121e3018bb12037" //48 bytes

Output- outStr* = {0x5a, 0x12, 0xb4, 0x3d, 0x31, 0x21, 0xe3, 0x01, 0x8b, 0xb1, 0x20, 0x37} //24 bytes
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
smanikar
  • 31
  • 1
  • 2
  • Why not make `outStr` an `std::ostream &` instead of `unsigned char *`? Then you could pass in an `std::ostringstream`, which is a bit safer than using a pointer. – cdhowie Oct 09 '14 at 04:20

1 Answers1

1

Allocate enough space for outStr before calling it.

bool StringToHex(const std::string &inStr, unsigned char *outStr)
{
    size_t len = inStr.length();
    for (size_t i = 0; i < len; i += 2) {
        sscanf(inStr.c_str() + i, "%2hhx", outStr);
        ++outStr;
    }
    return true;
}
timrau
  • 22,578
  • 4
  • 51
  • 64