Exercise 3-4 (itoa - Integer to string)
Chapter_3 Exercise_3-3 | utoa Exercise_3-5 |
Exercise 3-4 K&R, p. 64
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 INT_MIN, -2^(wordsize-1). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs.
Note: -INT_MIN gives an overflow warning and is replaced by INT_MIN on my computer, the same as INT_MAX+1 (two's_complement arithmetic). So we keep n negative, divide it by 10 repeatedly until it reaches 0. The test (n /= 10) > 0 is replaced by (n /= 10) != 0 as we may also work with negatives. For negative integers, n % 10 < 0, so we multiply it by sign == -1. See also Exercise_2-1.
itoa.c K&R, p. 64 download
#include <stdio.h> // for printf(), scanf()
#define SIZE 100 // array size (max no of digits)
// reverse s[], knowing its length:
void reverse(char s[], int len);
int itoa (int , char []); // int to string of chars
int main()
{
char digits[SIZE];
int n;
printf ("Give an integer: ");
scanf ("%d", &n);
itoa(n, digits);
printf ("%s\n", digits); // with an eventual sign
return 0;
}
// reverse s[], knowing its length:
void reverse(char s[], int len)
{
int i = 0, j = len-1;
char temp;
while (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
// get the digits of n into s[] (convert n to a string of characters),
// return the length of s[] (no of digits, plus an eventual sign):
int itoa (int n, char s[])
{
int i = 0, sign = 1;
if (n < 0)
{
sign = -1;
}
do
{ // get the digits in reverse order:
s[i++] = (n % 10)*sign + '0'; // get next (last read) digit
// if n < 0, (n /= 10) <= 0, (n % 10) < 0
} while (n /= 10); // while ((n /= 10) != 0); // delete last digit
if (sign < 0) {s[i++] = '-';} // first char after reverse
s[i] = '\0'; // end the string
reverse(s, i);
return i;
}
/*
gcc itoa.c -o itoa
./itoa
Give an integer: 0
0
./itoa
Give an integer: -1
-1
./itoa
Give an integer: 123
123
./itoa
Give an integer: -125
-125
./itoa
Give an integer: -2147483647 // INT_MIN+1
-2147483647
./itoa
Give an integer: -2147483648 // INT_MIN
-2147483648
./itoa
Give an integer: -2147483649 // INT_MIN-1
2147483647 // INT_MAX (underflow)
./itoa
Give an integer: -2147483650 // INT_MIN-2
2147483646 // INT_MAX-1 (modulo 2 arithmetic)
./itoa
Give an integer: 2147483647 // INT_MAX
2147483647
./itoa
Give an integer: 2147483648 // INT_MAX+1
-2147483648 // INT_MIN (overflow)
./itoa
Give an integer: 2147483649 // INT_MAX+2
-2147483647 // INT_MIN+1
*/
Chapter_3 Exercise_3-3 | BACK_TO_TOP | utoa Exercise_3-5 |
Comments
Post a Comment