0

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;
    }   
1
  • Either a simple lookup table piecing two nibbles into a pair of hex digit chars, or if performance is zero concern, creative use of sprintf. Either will get you where you need to be. Commented Aug 4, 2021 at 11:06

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your solution. How can I print this array? I'm trying with printf("*********** %c\n", hex_array[0]);, but a strange symbol appears in the terminal. Whit %s I've segmentation fault.
@WonderWhy This code should work. What is hex_array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.