Is there an easy way to convert a number to ASCII hexadecimal characters in C?

I am working on firmware for an embedded device. I want to send an array of hex char values ​​over a serial port. Is there an easy way to convert a value to ASCII hex?

For example, if the array contains 0xFF, I want to send the ASCII string "FF" or for the hex value 0x3B. I want to send "3B".

How is this usually done?

I already have serial send functions so that I can do this ...

char msg[] = "Send this message";
SendString(msg);

and the SendString function calls this function for each element in the passed array:

// This function sends out a single character over the UART
int SendU( int c)
{
    while(U1STAbits.UTXBF);
    U1TXREG = c;
    return c;
}

I am looking for a function that will allow me to do this ...

char HexArray[5] = {0x4D, 0xFF, 0xE3, 0xAA, 0xC4};
SendHexArray(HexArray);

//Output "4D, FF, E3, AA, C4"
+3
5

.

char *asciihex[] = {
    "00", "01", "02", ..., "0F",
    "10", "11", "12", ..., "1F",
    ...,
    "F0", "F1", "F2", ..., "FF"
};

...

SendString(asciihex[val]);

Edit

Dysaster nibbles:

void SendString(const char *msg) {
    static const char nibble[] = {'0', '1', '2', ..., 'F'};
    while (*msg) {
        /* cast to unsigned char before bit operations (thanks RBerteig) */
        SendU(nibble[(((unsigned char)*msg)&0xf0)>>4]); /* mask 4 top bits too, in case CHAR_BIT > 8 */
        SendU(nibble[((unsigned char)*msg)&0x0f]);
        msg++;
    }
}
+7

sprintf, SendString, UART. , , :

char num_str[3];
sprintf( num_str, "%02X", 0xFF );
SendString(num_str);

%02X printf, 0s 2 .

02 , , 0x0F, 0F F . x, (, ff ff).

+17

8- , shybble . 0 9 10 15. 16- .

void SendDigit(int c) {
    c &= 0x0f;
    c += (c <= 9) ? '0' : 'A'-10;
    SendU(c);
}

void SendArray(const unsigned char *msg, size_t len) {
    while (len--) {
        unsigned char c = *msg++;
        SendDigit(c>>4);
        SendDigit(c);
    }
}

. -, , ASCII. , EBCDIC, , "A" "F" ( ).

-, SendArray(). , , . , nibble[(*msg)>>4] , .

, . , , , . .

: ​​: 10 c + 'A' - 10, c + 'A'. , .

+10

sprintf .

sprintf (dest, "%X", src);

+2
source

If your compiler supports it, you can use itoa . Otherwise, I would use sprintf, as in the answers of Nathan and Mark. If itoa is supported and performance is a problem, try some testing to determine which is faster (past experience makes me expect itoa to be faster, but YMMV).

0
source

Source: https://habr.com/ru/post/1763997/


All Articles