Blob


1 /*
2 * Exercise 3-4. In a two's complement number representation, our version of
3 * itoa does not handle the largest negative number, that is, the value of n
4 * equal to -(2^(wordsize-1)). Explain why not. Modify it to print that value
5 * correctly, regardless of the machine on which it runs.
6 */
8 /* In the step n = -n, it is not possible to negate the largest negative
9 * number without integer overflow.
10 */
12 #include <string.h>
13 #include <stdio.h>
14 #include <limits.h>
16 void reverse(char s[]) {
17 int c, i, j;
18 for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
19 c = s[i];
20 s[i] = s[j];
21 s[j] = c;
22 }
23 }
25 void itoa(int n, char s[]) {
26 int i, sign;
27 unsigned u;
28 if ((sign = n) < 0)
29 u = -n;
30 i = 0;
31 do {
32 s[i++] = u % 10 + '0';
33 } while ((u /= 10) > 0);
34 if (sign < 0)
35 s[i++] = '-';
36 s[i] = '\0';
37 reverse(s);
38 }
40 int main() {
41 /* word size is 32 bits */
42 char s[100];
43 int i = -147483648;
44 itoa(i, s);
45 printf("Actual: %s\n", s);
46 printf("Expect: %s\n", "-147483648");
47 i = INT_MIN+1;
48 itoa(i, s);
49 printf("Actual: %s\n", s);
50 printf("Expect: %d\n", INT_MIN+1);
51 i = INT_MIN;
52 itoa(i, s);
53 printf("Actual: %s\n", s);
54 printf("Expect: %d\n", INT_MIN);
55 return 0;
56 }