Where is itoa() ?

24 May 2011

Am I missing something here but where's the itoa() function in the Mbed cloud compiler? I did try adding #include "stdlib.h" and #include <cstdlib> without luck.

#include "mbed.h"

DigitalOut myled(LED1);

int main() {
    int i;
    char *s;
    char fmtbuf[32];
    
    i = 100;
    s = itoa(i, fmtbuf, 16);
    printf("i in hex is %s\n", s);
    
    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}

Compiler reports:

Identifier "itoa" is undefined (E20)

24 May 2011

Looks like it's non-standard and not included. Why not just use sprintf?

24 May 2011

Thanks Igor. Was hoping to use a more "streamlined" function as opposed to the "brick through your window" that the *printf() family gives you. It'll have to do! ;)

24 May 2011

Instead of using printf you can use your "personal" itoa() function. The code is slim and simple (here K&R2 code). But you are right. itoa in standard libraries is the more comfortable way.

/* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;
 
     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }
18 Sep 2012

Love the mbed

Like C

Hate strings in C.....

Hi, I'm also attempting itoa as presented above, but reverse() does not seem to be implemented! Any updates/help to this code?

Many thanks

18 Sep 2012

Kevin,

The contents of the file reverse.c (from the SmallC 2.2 support library) -

/*
** reverse string in place 
*/
reverse(s) char *s; {
char *j;
int c;

  j = s + strlen(s) - 1;
  while(s < j) {
    c = *s;
    *s++ = *j;
    *j-- = c;
  }
}
12 May 2016

When You want to use custom base, the code can be modified like this:

include the mbed library with this snippet

char getNumber(int n){
  if(n>9) {
    return n-10+'a';
  } else {
    return n+'0';
  }
}
 void itoa(int n, char * s, int base_n)
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = getNumber(n % base_n);   /* get next digit */
     } while ((n /= base_n) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }