smanikar
smanikar

Reputation: 31

Convert Hex String to Bytes in C++

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

Upvotes: 2

Views: 5291

Answers (1)

timrau
timrau

Reputation: 23058

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;
}

Upvotes: 1

Related Questions