Exercise 3-5

Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) formats n as a hexadecimal integer in s.

We can start with itoa from Exercise 3-4 as a template.

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

Instead of performing mod 10 to get the next digit, we must instead perform mod b because in a base-b representation, each place value is a power of b rather than a power of ten. If the value of the digit exceeds 9, we can instead append digit - 10 + 'A'. This means the digit ten will be equal to 'A', the digit eleven will be equal to 'B', and so on.

    /* itoa:  convert n to characters in s */
    void itoa(int n, char s[])
    /* itob:  convert integer n into base b representation in string s */
    void itob(int n, char s[], int b)
    {
        int i, sign, digit;
    
        sign = (n >= 0) ? 1 : -1;
        i = 0;
        do {    /* generate digits in reverse order */
            digit = n % b * sign;
            s[i++] = n % 10 * sign + '0';   /* get next digit */
            /* use letters to depict digits greater than 9 */
            s[i++] = (digit < 10) ? digit + '0' : digit - 10 + 'A';
        } while (sign * (n /= b) > 0);
        if (sign == -1)
            s[i++] = '-';
        s[i] = '\0';
        reverse(s);
    }