简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM