Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hexadecimal to uint8_t in C++

Tags:

c++

hex

uint8t

I am working in C++ and let's say I have the following hexadecimal as a string

string key = "F3D5";

how can I convert it to an array of uint8_t?

Actually, I have an algorithm that generate a key of type uint8_t*, and I convert this key to hexadecimal using the following code :

uint8_t key = generateKey();
vector<uint8_t> keyVector(begin(key), end(key));
string hexadecimalKey= uint8_vector_to_hex_string(keyVector);

This is the method that convert uint8 vector to hexadecimal in string :

string uint8_vector_to_hex_string(const vector<uint8_t>& v) {
    stringstream ss;
    ss << hex << setfill('0');
    vector<uint8_t>::const_iterator it;

    for (it = v.begin(); it != v.end(); it++) {
        ss << setw(2) << static_cast<unsigned>(*it);
    }

    return ss.str();
}

And I would like to re-convert the hexadecimalKey to uint8_t, with the following code

uint8_t* convertedKey = hex_string_to_uint8_t(hexadecimalKey);

with the following method :

uint8_t* hex_string_to_uint8_t(string value) {
    size_t len = value.length();
    vector<uint8_t> out;
    for (size_t i = 0; i < len; i += 2) {
        std::istringstream strm(value.substr(i, 2));
        uint8_t x;
        strm >> std::hex >> x;
        out.push_back(x);
    }
    return out.data();
}

and whenever i do that, the convertedKey is not equal to key

I need your help.

Thank you, really appreciate it

like image 449
Elie Daher Avatar asked Nov 24 '25 20:11

Elie Daher


1 Answers

You can use the function below:

uint8_t* hex_str_to_uint8(const char* string) {

    if (string == NULL)
        return NULL;

    size_t slength = strlen(string);
    if ((slength % 2) != 0) // must be even
        return NULL;

    size_t dlength = slength / 2;

    uint8_t* data = (uint8_t*)malloc(dlength);

    memset(data, 0, dlength);

    size_t index = 0;
    while (index < slength) {
        char c = string[index];
        int value = 0;
        if (c >= '0' && c <= '9')
            value = (c - '0');
        else if (c >= 'A' && c <= 'F')
            value = (10 + (c - 'A'));
        else if (c >= 'a' && c <= 'f')
            value = (10 + (c - 'a'));
        else
            return NULL;

        data[(index / 2)] += value << (((index + 1) % 2) * 4);

        index++;
    }

    return data;
}

Good luck!

like image 66
Bilal EL CHAMI Avatar answered Nov 27 '25 10:11

Bilal EL CHAMI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!