Exercise 3.4 - itoa to handle largest negative integer


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.

The previous version of itoa was this:

void itoa() {

/* Modified version of itoa; to handle the situation of MIN_INT of limits.h
in the previous number = -2147483648 would fail at n =-n,because the max value of integer is 2147483647

modifying itoa to handle these situations. 
sign is stored as  the number itself, absolute value of each digit is stored in the string and 
while loop is tested not for 0

itoa: convert an integer to string */

#define MAXLINE 1000

#define abs(x) ( (x) > 0 ? (x): -(x))

void itoa(int n,char s[]);
void reverse(char s[]);

int main(void)
    int number;
    char str[MAXLINE];

 /* number=-2345645; */
    number = -2147483648;

    printf("Integer %d printed as\n String:",number);



    return 0;

void itoa(int n,char s[])
    int i,sign;


    i = 0;

        s[i++]= abs(n%10) + '0';
    if( sign < 0)



void reverse(char s[])
    int c,i,j;

Run this


In this version of itoa, which involves a largest negative number, we first store the number itself in an integer called sign. Then get numbers from unittest by doing n%10, get the unsigned number by doing a abs value and get character by adding it to 0.

Thus we go about converting each digit starting from unit place to a character. Once this process is over. We check if we were converting negative number, by checking if the sign is less than 0, if it was, we add a - to the string.

And then we do a simple reverse of the string to get our itoa.

Comments by Disqus