cstringtype-conversionhexuint8t

How to convert a uint8_t array into a string?


I've a function that can convert an hexadecimal string (ex. "02AFA1253...ecc.") into an uint8_t array. I would need to do the opposite, which is to convert the uint8_t array to a string of hexadecimal characters. How to do it? Here is the code of the function that converts hex string to uint8_t array: Thank you everybody for your help!

size_t convert_hex(uint8_t *dest, size_t count, const char *src) {
    size_t i = 0;
    int value;
    for (i = 0; i < count && sscanf(src + i * 2, "%2x", &value) == 1; i++) {
        dest[i] = value;
    }
    return i;
    }   

Solution

  • You want to do the opposite, so do the opposite.

    size_t convert_hex_inv(char *dest, size_t count, const uint8_t *src) {
        size_t i = 0;
        for (i = 0; i < count && sprintf(dest + i * 2, "%02X", src[i]) == 2; i++);
        return i;
    }
    

    Note that the buffer pointed at by dest has to be at least count * 2 + 1 elements. Don't forget the +1 for terminating null-character.