Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading