Tuesday, December 13, 2011

Own implementations

Own implementations of following fucntions

1.atoi()
2..memmove()      Also describe memmove() vs memcpy()..
3.copy()
4.printf()

atoi()
//STRING TO INTEGER
#include
#include
#include

int myatoi(const char *string);

int main(int argc, char* argv[])
{
printf("\n%d\n", myatoi("1998"));
getch();
return(0);
}

int myatoi(const char *string)
{
int i;
i=0;
while(*string)
{
i=(i<<3) + (i<<1) + (*string - '0');
string++;

// Dont increment i!
}
return(i);
}

itoa()
 void itoa(int n, char s[])
 {
     int i, sign;
 
     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }
 
 void reverse(char s[])
 {
     int i, j;
     char c;
 
     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
 } 

1 comment:

  1. //STRING TO INTEGER
    #include
    #include
    #include

    int myatoi(const char *string);

    int main(int argc, char* argv[])
    {
    printf("\n%d\n", myatoi("1998"));
    getch();
    return(0);
    }

    int myatoi(const char *string)
    {
    int i;
    i=0;
    while(*string)
    {
    i=(i<<3) + (i<<1) + (*string - '0');
    string++;

    // Dont increment i!

    }
    return(i);
    }

    ReplyDelete