AnsweredAssumed Answered

itoa() and uitoa() in Redlib

Question asked by LPCware Support on Mar 31, 2016

itoa() is non-standard library function which is provided in many other toolchains to convert an integer to a string. To ease porting, the LPCXpresso IDE provides two variants of this function in the Redlib C library....

char * itoa(int value, char *vstring, unsigned int base); 
char * uitoa(unsigned int value, char *vstring, unsigned int base);

which can be accessed via the system header....

#include <stdlib.h>

itoa() converts an integer value to a null-terminated string using the specified base and stores the result in the array pointed to by the vstring parameter. base can take any value between 2 and 16; where 2 = binary, 8 = octal, 10 = decimal and 16 = hexidecimal.

If base is 10 and the value is negative, then the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned.

The return value to the function is a pointer to the resulting null-terminated string, the same as parameter vstring.

uitoa() is similar but treats the input value as unsigned in all cases.

Note that the caller is responsible for reserving space for the output character array - the recommended length is 33, which is long enough to contain any possible value regardless of the base used.

Example invocations

    char vstring [33];
    itoa (value,vstring,10); // convert to decimal
    itoa (value,vstring,16); // convert to hexadecimal
    itoa (value,vstring,8);; // convert to octal

Standards compliance

As noted above, itoa() / uito() are not standard C library functions. A standard-compliant alternative for some cases may be to use sprintf():

     sprintf(vstring,"%d",value); // convert to decimal 
     sprintf(vstring,"%x",value); // convert to hexadecimal
     sprintf(vstring,"%o",value); // convert to octal

NOTE : The Newlib C library does not provide implementations of itoa() / uitoa().

Outcomes