Nostra
Nostra

Reputation: 53

Convert unsigned integer with hexdecimals to string

I have an _u8 Array with hexadecimals in it, in the form of: A81B6A9D4D2E for example. And I want to turn it into an string in the form of: A8-1B-6A-9D-4D-2E and have it as a string to send it.

#define SL_MAC_ADDR_LEN     UINT8_C(6)
_u8 wlanMacAddressVal[SL_MAC_ADDR_LEN];

I can print it with a Loop as following:

for(int i = 0; i < SL_MAC_ADDR_LEN; i++){
printf(%X, wlanMacAddressVal[i]);
printf("-");
}

But when I try to make a string/chararray and using the strcat Function my results are always weird symbols.

I've tried using sprintf() in the loop, but it always overwrites the last hexadecimals

sprintf(wlanMacString,"%X",(_u8 *)wlanMacAddressVal[i]);

Upvotes: 1

Views: 326

Answers (2)

0___________
0___________

Reputation: 67476

If you are on the resurce limited hardware (for example uC) using sprintf is not a good idea.

static const char digits[]="0123456789ABCDEF";

char *bytetostr(char *buff, const uint8_t val)
{
    buff[0] = digits[val >> 4];
    buff[1] = digits[val & 0x0f];
    buff[2] = 0;
    return buff;
}


char *bytearrtostring(char *buff, const uint8_t *arr, size_t length, const int separator)
{
    char *result = buff;

    while(length)
    {
        bytetostr(buff, *arr++);
        if(--length)
        {
             buff[2] = separator;
             buff += 3;
        }
    }
    buff = 0;

    return result;
}

int main()
{
    uint8_t array[] = {0xa1, 0x45, 0xde, 0x67, 0xff, 0x00};

    char buff[100];

    printf("%s\n", bytearrtostring(buff, array, sizeof(array), '-'));
}

You can experiment yourself https://onlinegdb.com/HJy5KGLyS

https://godbolt.org/z/3bQa1-

Upvotes: 3

kiran Biradar
kiran Biradar

Reputation: 12732

Use sprintf with 02x format specifier.

char buf[SL_MAC_ADDR_LEN*3]; //2*number of hex bytes + number of `-` symbols + \0.


char *p = buf;
for (int i=0;i<SL_MAC_ADDR_LEN;i++)
  p += sprintf(p, i ? "-%02hhx":"%02hhx", _u8Array[i]);

Note that you need to advance p to skip number of bytes printed so far in the buffer.

Upvotes: 3

Related Questions