繁体   English   中英

如何将 `std::string` 十六进制值转换为 `unsigned char`

[英]How do you convert a `std::string` hex value to an `unsigned char`

样本输入

a8 49 7f ac 24 77 c3 6e 70 ca 99 ca fc e2 c5 7b

此函数将样本中的十六进制值转换为字符串,以便稍后转换为无符号字符

std::vector<unsigned char> cipher_as_chars(std::string cipher) 
{
    std::vector<unsigned char> hex_char;
    int j =0 ;
    for (int i = 0; i < cipher.length();)
    {

        std::string x = "";
        x = x + cipher[i] + cipher[i+1];
        
        unsigned char hexchar[2] ;
        strcpy( (char*) hexchar, x.c_str() );
        hex_char[j] = *hexchar;
        j++;


        
        cout << "Current Index : " << i << " " << x  << " <> " << hexchar << endl;
        i = i+3;
    }


    return hex_char;
}

作为一个非常简单的解决方案,您可以使用istringstream ,它允许解析十六进制字符串:

#include <cstdio>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

std::vector<unsigned char> cipher_as_chars(std::string const& cipher) {
    std::istringstream strm{cipher};
    strm >> std::hex;

    return {std::istream_iterator<int>{strm}, {}};
}

int main() {
    auto const cipher = "a8 49 7f ac 24 77 c3 6e 70 ca 99 ca fc e2 c5 7b";
    auto const sep = cipher_as_chars(cipher);
    for (auto elm : sep) {
        std::printf("%hhx ", elm);
    }
    std::putchar('\n');
}

暂无
暂无

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

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