Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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.
- */
- /*
- * 2^31 = 0x8000 =
- * 10000000000000000000000000000000
- * when extecuting n =-n it results to the same number, and n remains negative
- * number. n%10 is reults in a negative number in that case.
- */
- #include <stdio.h>
- #include <string.h>
- /* reverse: reverse string s in place */
- 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;
- unsigned int un = n;
- if ((sign = n) < 0) /* record sign */
- un = -n; /* make n positive */
- i = 0;
- do { /* generate digits in reverse order */
- s[i++] = un % 10 + '0'; /* getnextdigit */
- } while ((un /= 10) > 0);
- if (sign < 0)
- s[i++] = '-';
- s[i] = '\0';
- reverse(s);
- }
- int
- main(int argc, char **argv)
- {
- char s[100];
- itoa(2147483648, s);
- printf("%s\n", s);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment