Converting Integer to Characters in Ansi C

feedinco

One of the problem in Embedded C (programming C in a microctonroller) is that you cannot declare a variable of type String, but you can use an Array of Charachters (char[]). One example where this example can be used is when you have an integer value (lets say 125 degrees) and you need to display it onto an LCD. The LCD accepts ascii characters and you need to send '1', '2' and '5'. 

By using the below method it can be easily done. 


Converting an integer to an Array of Characters 


 #include < reg51.h >


 void main()
 {
int number = 1234;
char count = 0;
char stringy[4] = {'0','0','0','0'};
if (number != 0)
{
   while (number>0)
   {
       stringy[count]=(number%10)+48;
       number/=10;
count++;
   }
//count = lenght of the char
//stringy will ocntain all the characters in an array :)
}
 }


feedinco

Comments