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:
Here's the function I wrote:
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!
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.
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!








