Exercise 3-4

In a two's complement number representation, our version of itoa does not handle the largest negative number, that is, the value of n equal to -(2wordsize-1). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs.

In a two's complement machine, the largest negative value is one more than the largest positive value because the leftmost place value is -2n, while the remaining n - 1 bits dedicated for positive values can represent up to 2n - 1 (e.g. 10000000binary is one more than 01111111binary.) In itoa, when n is a negative number, we assign -n to n which is why the code does not work with the largest negative number.

To fix this, we can instead set sign to -1 or 1 depending on the value of n whilst leaving n unchanged. Then, when we calculate the digits of n, we also multiply them by sign. That way, if n is negative, multiplying each digit by sign will cancel out the minus. If n is nonnegative, multiplying by sign will have no effect since sign will be equal to one.

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