# How to convert a number to C string

H

Unfortunately in embedded systems sometimes it is not feasible to use strtol function to convert an integer to c string. Using the following C function you will be able to convert any string to an integer number. Although it is not an optimal solution but it will help you solve this kind of problem.

Updated Version Here

(Please do not hesitate to provide any better alternative method)

``````double power (double X, int Y)
{
int i;
double value = 1;
for (i = 0; i < Y; i++)
value *= X;
return value;
}

char * int_to_string(int value)
{
int num_of_digits=1;
int position = 0;
int temp = value;
char * result;

while ((temp = temp / 10) != 0)
num_of_digits++;

result= (char *) malloc( (num_of_digits + 1) * sizeof(char) );

do
{
*(result+ position) = ((value - (value % (int) power(10, ((num_of_digits- 1) - position))))
/ (int) power(10, ((num_of_digits- 1) - position))) +48;
value -= (value - (value % (int) power(10, ((num_of_digits- 1) - position))));
}
while( (++position) != num_of_digits );

*(result + (num_of_digits)) = '';
return result;
}``````

Also have a look at the following useful C functions: atoi, atof, atol.