c++cteensy

How to convert uint16_t number to ASCII HEX?


What is the best way to convert a unsigned 16 bit integer into ASCII HEX? I'm trying to integrate my Arduino with a serial communication protocol that expects the payload as an array of 2 byte ASCII HEX values. I'd like to be able to store each character of the HEX representation in a char array since the full message (with start and stop characters) needs to be CRC checksummed before being transmitted.

For example, to transmit a decimal value of 129, it would expect a string 0081 (0x00 and 0x81). To transmit a decimal value of 35822, it would expect a string of 8BEE.

I mostly work with Python so I'm not very familiar with casting to different data types.

Thanks!

EDIT: I'm actually working with a Teensy 4.0, just wrote Arduino out of habit


Solution

  • static const char *digits = "0123456789ABCDEF";
    
    char *toHex(char *buff, uint16_t val, int withNULL)
    {
        buff[0] = digits[(val >> 12)];
        buff[1] = digits[((val >> 8) & 0xf)];
        buff[2] = digits[((val >> 4) & 0xf)];
        buff[3] = digits[(val & 0xf)];
        if(withNULL) buff[4] = 0;
        return buff;
    }
    
    char *toHex1(char *buff, uint16_t val, int withNULL)
    {
        unsigned char d;
        buff[0] = (char)((d = (val >> 12)) > 9 ? ('A' + d - 10) : ('0' + d));
        buff[1] = (char)((d = ((val >> 8) & 0xf)) > 9 ? ('A' + d - 10) : ('0' + d));
        buff[2] = (char)((d = ((val >> 4) & 0xf)) > 9 ? ('A' + d - 10) : ('0' + d));
        buff[3] = (char)((d = (val & 0xf)) > 9 ? ('A' + d - 10) : ('0' + d));
        if(withNULL) buff[4] = 0;
        return buff;
    }