Home > Software engineering >  About atoi function
About atoi function

Time:10-30

`

#include <unistd.h>

int ft_atoi(char *str)
{
    int c;
    int sign;
    int result;

    c = 0;
    sign = 1;
    result = 0;
    while ((str[c] >= '\t' && str[c] <= '\r') || str[c] == ' ')
    {
        c  ;
    }
    while (str[c] == ' ' || str[c] == '-')
    {
        if (str[c] == '-')
            sign *= -1;
        c  ;
    }
    while (str[c] >= '0' && str[c] <= '9')
    {
        result = (str[c] - '0')   (result * 10);
        c  ;
    }
    return (result * sign);
}

#include <stdio.h>

int main(void)
{
    char *s = " --- -- 1234ab567";
    printf("%d", ft_atoi(s));
}

`

This line: result = (str[c] - '0') (result * 10); Why do we subtract zero and multiply by 10? How its convert ascii to int with this operations? Thanks...

CodePudding user response:

Some detail before answering your question

Internally everything is a number a char is not an exception. In C char is a promoted type of integer meaning characters are integer in C. The char which is promoted type of integer are mapped to responding ASCII Value.

For example:

Capital Letter Range

65 => 'A' to 90 => 'Z'

Small Letter Range

97 => 'a' to 122 => 'z'

Number Range

48 => '0' to 57 => '9'

To answer your question

The ASCII CHARACTER '0' subtracted from any ASCII CHARACTER that is a digit(0-9) results to an actual Integer.

For Example

'9'(57) - '0'(48) = 9 (int)
'8'(56) - '0'(48) = 8 (int)

Remember char are promoted integer in C Read the detail to understand this statement.

And Also the ASCII CHARACTER '0' added to any INTEGER in the range(0-9) results to an ASCII CHARACTER.

For Example

9   '0'(48) = '9'(57) (char)
8   '0'(48) = '8' (56)(char)

CodePudding user response:

Please see ASCII table

The ASCII code for '0' is 48 - not zero. Therefore, to convert to decimal you need to subtract 48

  •  Tags:  
  • c
  • Related