Archive for the ‘C’ Category

itoa

9. April 2010

No Comments »

Convert an integer to an ASCII string

/* K&R2 60-63 */
char *itoa(int n, char s[])
{
    int c, i, j, sign;

    if((sign = n) < 0)
        n = -n;

    do {
        s[i++] = n % 10 + '0';
    } while((n /= 10) > 0);

    if(sign < 0)
        s[i++] = '-';

    s[i] = '\0';

    for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }

    return s;
}