Cast byte array to char array

I'm trying to write an IP address stored in a byte array to a char array which will show the IP address on a display ;

byte ip[] = { 192, 168, 0, 100 };
char writedisplay[120];

(writedisplay is 120 elements big as I'm using it for something else later)

I'm guessing I would need to write a function that determines how many digits each byte element in the byte array is, then convert each digit of each element to a char and write it out to the char array.

But is there a function that will do this for me without costing too much memory?

But is there a function that will do this for me

sprintf().

without costing too much memory?

I can't remember.

What kind of memory are you hand-waving about?

What am I missing? If the biggest single value of the IP is 3 digit characters and you want to display them as a string, separated by periods, doesn't that work out to be 4 * 3 + 4 = 16, including the null at the end of the string. Why 120 elements?

Thanks all

@econjack

Why 120 elements?

See my original post: "(writedisplay is 120 elements big as I'm using it for something else later)"

pepe's suggestion:

byte ip[] = { 192, 168, 0, 100 };
char writedisplay[120];

// ip: 4-byte input array
// str: 16-char output buffer
void IPtoString(unsigned char* ip, char* str)
{
  int i = 4;
  for (;;) {
    unsigned char f1 = *ip % 10;
    unsigned char f100 = *ip / 10; 
    unsigned char f10 = f100 % 10;
    f100 /= 10;
    if (f100) {
      *str++ = '0'+f100;
      *str++ = '0'+f10;
    } else if (f10)
      *str++ = '0'+f10;
    *str++ = '0'+f1;
    if (!--i) {
      *str = '\0';
      return;
    }
    *str++ = '.';
    ip++;
  }
}
  
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  
  IPtoString (ip, writedisplay);
     
  Serial.println (writedisplay);
 
  }  // end of setup

void loop () { }

Size:

Binary sketch size: 2,096 bytes (of a 32,256 byte maximum)

PaulS's suggestion:

byte ip[] = { 192, 168, 0, 100 };
char writedisplay[120];

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  sprintf (writedisplay, "%i.%i.%i.%i", ip [0], ip [1], ip [2], ip [3]);
  Serial.println (writedisplay);
 
  }  // end of setup

void loop () { }

Size:

Binary sketch size: 3,508 bytes (of a 32,256 byte maximum)

My own attempt, using itoa:

byte ip[] = { 192, 168, 0, 100 };
char writedisplay[120];

void appendInt (const int what, char * &p)
  {
  itoa (what, p, 10);
  p += strlen (p);
  }
  
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  
  char * buf = writedisplay;
  for (byte i = 0; i < 4; i++)
     {
     appendInt (ip [i], buf);
     if (i < 3)
       *buf++ = '.';
     }
     
  Serial.println (writedisplay);
 
  }  // end of setup

void loop () { }

Size:

Binary sketch size: 2,222 bytes (of a 32,256 byte maximum)

pepe seems to win on size, however PaulS would probably win if you were already using sprintf elsewhere, because you would be using the extra library code anyway.