Array to String help

I have this function:

void array_to_string(byte array[], unsigned int len, char buffer[])
{
   for (unsigned int i = 0; i < len; i++)
   {
      byte nib1 = (array[i] >> 4) & 0x0F;
      byte nib2 = (array[i] >> 0) & 0x0F;
      buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
      buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
   }
   buffer[len*2] = '\0';
}

The result that I get is:

F555B31F

What do I need to change in this function to get the result (colons added):
F5:55:B3:1F

I'm new to C/C++, so please be gentle :blush:

In practice, is "len" the same value every time you use this function?

1 Like

If i equals 2, 5 or 8 (There are neat ways to do this using the modulo operator (%) ) put a colon in the array and increment i.

1 Like

You are writing the two nibbles already, just add a line to write the colon to the buffer after you write the second nibble in your for loop. Make sure to use buffer[i+3+0] , buffer[i+3+1] etc.

BTW: buffer[len*2] is wrong, you probably meant buffer[len*2-1] instead. Make sure to also change this to buffer[len*3-1] if you add the colon after the bytes.

Edit: sorry, my last paragraph is wrong. Don't subtract 1 ...

1 Like
void array_to_string(byte array[], unsigned int len, char buffer[])
{
   for (unsigned int i = 0; i < len; i++)
   {
      if (i == 0)
        sprintf(buffer, "%02x", array[i]);
      else
        sprintf(&buffer[i*3-1], ":%02x", array[i]);
   }
}
1 Like

Thank you guys for your quick responses.

@PaulRB yes the len is always 4

@PaulRB is there a way to get it always uppercase?

Oh, yes, sorry. Change the "x" to "X" in sprintf().

1 Like

Then you don't need array_to_string() at all:

byte array[4] = { 0xF5, 0x55, 0xB3, 0x1F };
char buffer[12];
...
sprintf(buffer, "%02X:%02X:%02X:%02X", array[0], array[1], array[2], array[3]);
1 Like
void array_to_string(byte array[], unsigned int len, char buffer[])
{
   for (unsigned int i = 0; i < len; i++)
   {
      if (i == 0)
        sprintf(buffer, "%02x", array[i]);
      else
        sprintf(&buffer[i*3-1], ":%02x", array[i]);
   }
}

@sakshijn are you suggesting a change? I didn't spot it.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.