Jump to content






Photo

Writing an ITOA function

Posted by Robotics Guy, in Programming 26 August 2011 · 674 views

programming
A recent project I worked on was interfacing an accelerometer to a PIC18F4550 and displaying the sensor data on an HD44780 display. When writing my HD44780 framework code(check out the HD44780 tutorial), I needed a way to convert the accelerometer data - which was an integer number - to ASCII data, so that it could be outputted to the LCD. I try not to use other people's libraries simply because I want to do things myself so that I can get the learning experience, so I had to come up with a way to convert integer data to ASCII data. After some research, I found a very simple solution to this problem: the Integer TO Ascii function (ITOA).

Here's how the ITOA function works:
  • Start with your integer number. For example, 501.
  • Perform a modulo operation on your number with a divisor of 10. E.g. 501 % 10.
  • The result will be the remainder of the division; in the above example, the remainder will be 1.
  • Either add 48 ( "0" on the ascii chart) or '0' (with the single quotes) to the above remainder, and the resulting number will be the decimal representation of the number (1) in ASCII!
  • Divide the number by 10 to discard the least significant digit.
  • Repeat for additional digits.
Pretty easy, right? Well, it is! There is, however, one potential problem with the above method, and that is digits are converted last to first (i.e. "1" is converted, then "0," then "5"), so if you store the ASCII digits in a character array in the order you convert them, they will be backwards. The solution is to store the digits backwards. That is, if we have a char array name charArray that is three bytes in size, then we would store the first converted digit "1" in charArray[2], digit "0" in charArray[1], and digit "5" in charArray[0].

Here's the function I wrote:

void LCD_itoa (int num, unsigned char* dest) // Converts integer number to a string and stores in passed array
{
    int itoa_i = 0;
    int digits = 0;
    
	// Get the number of digits
    if(num >= 1000)
        digits = 4;
    else if(num >= 100)
            digits = 3;
        else if(num >= 10)
                digits = 2;
            else
   	             digits = 1;
    
    // Convert digits to ascii and put in dest array
    for(itoa_i = (digits-1); itoa_i >= 0; itoa_i--)
    {
    	*(dest + itoa_i) = num%10 + '0'; // '0' + int = ascii representation of int
    	num /= 10; // discard least significant digit
    }
    *(dest + digits) = 0; // Null terminate the string
}

The function accepts an integer number and a pointer to the destination as parameters. Inside the function, the number of digits is determined based on the size of the number, then the conversion takes place.

There you have it - a working ITOA function!





or Sign In

Recent Comments

Sponsors