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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

/* 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 */
i = 0;
do { /* generate digits in reverse order */

s[i++]=n%10+'0'; /*getnextdigit*/
    } while ((n /= 10) > 0);  /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
}
/* delete it */



For the program structure, is quite obvious:

keep dividing n by 10 and add '0' to get it`s ascii character value until expression is zero?
Some clarification about the program would be welcome.

Program does not handle largest negative number because integer overflow. There is one more positive value '0' for positive integers. How should I fix that?
Last edited on
If the number is negative then get the first digit of the negative number directly. Then divide by 10 change the sign and continue.
Hi,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

#include <stdio.h>
#include <string.h>




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;
  
  if ((sign = n) < 0)    /* record sign */
     n = -n;             /* make n positive */
  i = 0;
  do {
	  s[i++] = n % 10 + '0';  /* get next digit */
  }  while ((n /= 10) > 0);   /* delete it */
  if (sign < 0)
	  s[i++] = '-';
  
  s[i] = '\0';
  reverse(s);

}



int main()
	
{
   int number;
   char str[1000];
   
   number = -20;
   
   printf( "Integer %d printed as string\n", number);
   
   itoa(number, str);
   
   printf("%s", str);
   
   return 0;
   
}




I don`t understand why it`s giving me -20. Or how is the program supposed to work.
Topic archived. No new replies allowed.