Exercise 3.4 - itoa to handle largest negative integer¶
Question¶
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
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
#define abs(x) ((x) > 0 ? (x) : -(x))
void reverse(char s[]) {
int c, i, j;
for (i = 0, j = strlen(s) - 1; i < j; i++, j--)
c = s[i], s[i] = s[j], s[j] = c;
}
void itoa(int n, char s[]) {
int i, sign;
sign = n;
i = 0;
do {
s[i++] = abs(n % 10) + '0';
} while ((n /= 10) != 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
int main(void) {
int number;
char str[MAXLINE];
/* number=-2345645; */
number = -2147483648;
printf("Integer %d printed as\n String:", number);
itoa(number, str);
printf("%s", str);
return 0;
}
Explanation¶
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.