简体   繁体   English

在C ++中将十六进制字符串转换为字节

[英]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. 我正在寻找一个C ++库函数或内置函数,该函数可以读取长的十六进制字符串(例如SHA256哈希)并将其转换为无符号char数组。 I tried using stringstream for this but to no avail. 我尝试为此使用stringstream但无济于事。

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. 调用之前为outStr分配足够的空间。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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