Convert Int to Decimal Example

From Pinguino
Jump to: navigation, search


Here is an example of how to convert an integer value to a decimal value so you can send it to your LCD.

Leading zeros will NOT be blanked. Feel free to add this capability. Maybe I will if I feel the need for it.


// Example how to convert an integer value to a decimal string that you can send to your LCD
// Kurt Schatteman - 2010

void Int2Char(char *Result, unsigned int ToConvert)
{  
  uchar Digit[5];
  int c;
  unsigned int H1,H2,H3;
	
  H1=ToConvert;
  H2=0;
  H3=10000;	                        // Needed because PinguinoC lacks pow function.
	
  for (c=4;c>=0;c--)
  {
    Digit[c] = H1/H3;
    H1=ToConvert-Digit[c]*H3-H2;
    H2=H2+Digit[c]*H3;
    H3=H3/10;
    Result[4-c]=Digit[c]+48;
  }
}  
    
Int2Char can be optimized (proposed by André Gentric - 25/02/201:

void Int2Char(char *Result, unsigned int ToConvert)
{  
  uchar Digit[5];
  int c;
  unsigned int H1,H2;
	
  H1=ToConvert;
  H2=10000;	                        // Needed because PinguinoC lacks pow function.
	
  for (c=4;c>0;c--)
  {
    Digit[c] = H1/H2;
    H1 %=H2;                           // use of modulo operator or H1 = H1 - Digit[c]*H2
    H2=H2/10;
    Result[4-c]=Digit[c]+48;
  }
  Result[4]=H1+48;
}

 
void loop() 
{
  char Decimal[5];                // This array of char will hold the endresult of Int2Char   			 
  unsigned int Test;              // This will hold the int you want to be converted

  Test=25864;
  Int2Char(Decimal,25864);        // Convert int to a decimal value and place it in array Decimal
  // send Decimal to your LCD here
}