Page 64

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 -(2 to the power (wordsize - 1)). Explain why not. Modify it to print that value correctly regardless of the machine on which it runs.

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

#define LEN 1000

/* The solution involves an implementation of itoa that doesn't require negative numbers
 * to be flipped to positive, as this will never work. */

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

int main()
{
	char s[LEN];

	itoa2(-1234, s);

	printf("%s", s);
}

void itoa2(int n, char s[])
{
	int i, sign;
	sign = n < 0 ? -1 : 1;

	i = 0;
	do {
		s[i++] = (n % 10 * sign) + '0';
	} while ((n /= 10) != 0);
	if (sign < 0)
		s[i++] = '-';
	s[i] = '\0';
	reverse(s);
}

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

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

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;
	}
}