Sunday, July 16, 2006

String to Integer, Integer to String( itoa, atoi )

itoa and atoi
Start number at 0
If the first character is '-'
--Set the negative flag
--Start scanning with the next character
For each character in the string
--Multiply number by 10
--Add (digit character - '0') to number
Return number
int StrToInt (char str[])
{
int i = 0, isNeg = 0, num = 0;
if (str[0] == '-')
{
isNeg = 1;
i = 1;
}
while (str[i])
{
num *= 10;
num += (str[i++] - '0'); }
if (isNeg)
num *= -1;
return num;
}

If number less than zero
--Multiply number by -1
--Set negative flag
While number not equal to 0
--Add '0' to number % 10 and write this
--Integer divide number by 10
If negative flag is set
--Write '-' into next position in temp buffer
Write characters in temp buffer into output
Terminate output string with a NULL.
#define MAX_DIGITS_INT 10
void IntToStr(int num, char str[])
{
int i = 0, j = 0, isNeg = 0;
/* Buffer big enough for largest int, - sign and NUL */
char temp[MAX_DIGITS_INT + 2];
/* Check to see if the number is negative */
if (num < isneg =" 1;"> 0)
str[j++] = temp[--i];
/* NUL terminate the string */
str[j] = '\0';
}

No comments:

Post a Comment