简体   繁体   中英

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

sample input

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

This fucntion converts the hex values in the sample to a string to be later converted into an unsigned char

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

As a very simple solution, you can use a istringstream , which allows parsing hex strings:

#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');
}

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