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

Time:01-02

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

CodePudding user response:

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');
}
  •  Tags:  
  • c
  • Related