How to convert char to hex stored in uint8_t form?

Tyron Maples picture Tyron Maples · Feb 22, 2012 · Viewed 27k times · Source

Suppose I have these variables,

const uint8_t ndef_default_msg[33] = {
    0xd1, 0x02, 0x1c, 0x53, 0x70, 0x91, 0x01, 0x09,
    0x54, 0x02, 0x65, 0x6e, 0x4c, 0x69, 0x62, 0x6e,
    0x66, 0x63, 0x51, 0x01, 0x0b, 0x55, 0x03, 0x6c,
    0x69, 0x62, 0x6e, 0x66, 0x63, 0x2e, 0x6f, 0x72,
    0x67
};
uint8_t *ndef_msg;
char *ndef_input = NULL;

How can I convert ndef_input (which is just a plain text, like "hello") to hex and save into ndef_msg? As you can see ndef_default_msg is in hex form. Data inside ndef_msg should be something like that as well.

A bit of background, in the original program (source code), the program will open a file, get the data and put it inside ndef_msg, which then will be written into a card. But I don't understand how it can take the data and convert to hex.

I want to simplify the program so it will directly ask user for text (instead of asking for a file).

Answer

foo picture foo · Feb 22, 2012

Why not read it into ndef_msg directly, (minus the \0 if it suppose to be a pure array). The hex are just for presentation, you could have just picked decimal or octal with no consequence for the content.

void print_hex(uint8_t *s, size_t len) {
    for(int i = 0; i < len; i++) {
        printf("0x%02x, ", s[i]);
    }
    printf("\n");
}

int main()
{
    uint8_t ndef_msg[34] = {0};

    scanf("%33s", ndef_msg);
    print_hex(ndef_msg, strlen((char*)ndef_msg));


    return 0;
}

You probably need to handle the reading of the string differently to allow for whitespace and perhaps ignore \0, this is just to illustrate my point.