Saturday, February 20, 2010

C Tips: Converting a char array of numbers into a integer

This is a simple tip for those who can't use any C++ libs, when you are programming a uP for example.
It doesn't matter how you got the numbers in that array, the tip here is just how you are going to take them out, in that specific order.

You multiply by 10 and sum them. Line 19.


#include 

int main()
{
   // This is the declaration
   char  nChar[5];

   // I have to assign the numbers to the array
   nChar[0] = (char) 3;
   nChar[1] = (char) 9;
   nChar[2] = (char) 6;
   nChar[3] = (char) 5;
   nChar[4] = (char) 0;

   int numberInt = 0;

   // This is how it is done
   for (int a = 0; a < 4; a++)
     numberInt = (numberInt * 10) + ((int)nChar[a]);

   printf("%d", numberInt);
}


Renan

No comments:

Post a Comment