khalfella

ansi_c_pg059_ch03_ex04.c

Dec 27th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. /*
  2. * Exercise 3-4.
  3. * In a two's complement number representation, our version of itoa does not
  4. * handle the largest negative number, that is, the value of n equal to
  5. * -(2wordsize-1). Explain why not.Modify it to print that value correctly,
  6. * regardless of the machine on which it runs.
  7. */
  8.  
  9.  
  10.  
  11. /*
  12. * 2^31 = 0x8000 =
  13. * 10000000000000000000000000000000
  14. * when extecuting n =-n it results to the same number, and n remains negative
  15. * number. n%10 is reults in a negative number in that case.
  16. */
  17.  
  18.  
  19. #include <stdio.h>
  20. #include <string.h>
  21. /* reverse: reverse string s in place */
  22. void
  23. reverse(char s[])
  24. {
  25. int c, i, j;
  26. for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
  27. c = s[i];
  28. s[i] = s[j];
  29. s[j] = c;
  30. }
  31. }
  32.  
  33.  
  34. void
  35. itoa(int n, char s[])
  36. {
  37. int i, sign;
  38. unsigned int un = n;
  39. if ((sign = n) < 0) /* record sign */
  40. un = -n; /* make n positive */
  41. i = 0;
  42. do { /* generate digits in reverse order */
  43. s[i++] = un % 10 + '0'; /* getnextdigit */
  44. } while ((un /= 10) > 0);
  45. if (sign < 0)
  46. s[i++] = '-';
  47. s[i] = '\0';
  48. reverse(s);
  49. }
  50.  
  51. int
  52. main(int argc, char **argv)
  53. {
  54. char s[100];
  55. itoa(2147483648, s);
  56. printf("%s\n", s);
  57. return (0);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment