Q:

Write your own atoi() in c

0

The atoi() is a c library function used to convert a numeric string to his integer value.

Steps to create own atoi().

The atoi() only convert a numeric string to their integer value, so check the validity of the string. If any non-numeric character comes, the conversion will be stopped.

Subtract 48 (ASCII value of 0) from the string character to get the actual value and perform some arithmetical operation.

for example,

If the numeric string is “124”, we know that ASCII value of ‘1’, ‘2, and ‘4’ is 49, 50 and 52 respectively. So if we subtract 48 from these numeric characters we will get the actual numeric value 1,2 and 4.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include<stdio.h>
#define Is_NUMERIC_STRING(d) (*(char*)d >= 48) && (*(char*)d<= 57)
int StringToInt(const char *pszBuffer)
{
    int result=0; // variable to store the result
    int sign = 1; //Initialize sign as positive
    if(pszBuffer == NULL) //If pointer is null
        return 0;
    //If number is negative, then update sign
    if((*pszBuffer) == '-')
    {
        sign = -1;
        ++pszBuffer; //Increment the pointer
    }
    
    while( Is_NUMERIC_STRING(pszBuffer)) //check string validity
    {
        result = (result*10)+ (*pszBuffer-48);
        pszBuffer++; //Increment the pointer
    }
    return (sign * result);
}
int main()
{
    int d;
    d = StringToInt("-1230");
    printf("%d\n",d);
    return 0;
}

Output: -1230

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Reverse a string in c without using a library func... >>
<< Searching for a pattern in a given string...