3.4.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. void itoa(int n, char s[]);
  3. void reverse(char s[]);
  4. int clear(char* c, int count);
  5. #define MAGIC_1 2048
  6. #define MIN_INT -2147483648
  7. /** the int range is from -2147483648 to 2147483647 */
  8. /** the highest bit 2147483648 is the bit for 'negative' */
  9. /** it goes there are 2147483648 numbers below 0, 2147483647 above 0 and 0 */
  10. int main()
  11. {
  12. char s[MAGIC_1];
  13. int k= -1;
  14. // int l = -k;
  15. //printf("l: %i\n",l);
  16. // itoa( -2147483648,s);
  17. // printf("%s\n",s);
  18. for(;;)
  19. {
  20. clear(s,MAGIC_1);
  21. itoa(k,s);
  22. printf("%i :\t %s\n",k,s);
  23. k*=2;
  24. }
  25. return 0;
  26. }
  27. /* itoa: convert n to characters in s */
  28. int clear(char* c, int count)
  29. {
  30. for (int i=0; i<count;i++)
  31. {c[i]=0;}
  32. return 0;
  33. }
  34. void itoa(int n, char s[])
  35. {
  36. int i, sign, specialcase=0;
  37. if ((sign = n) < 0) /* record sign */
  38. {
  39. if (n != MIN_INT)
  40. n = -n; /* make n positive */
  41. else //special case
  42. {
  43. n++;
  44. n = -n;
  45. specialcase=1;
  46. }
  47. }
  48. i = 0;
  49. do { /* generate digits in reverse order */
  50. if ((i == 0) && specialcase )
  51. {
  52. s[i++] = n % 10 + '1';
  53. }/* get next digit */
  54. else
  55. {
  56. s[i++] = n % 10 + '0'; /* get next digit */
  57. }
  58. }
  59. while ((n /= 10) > 0); /* delete it */
  60. if (sign < 0)
  61. s[i++] = '-';
  62. s[i] = '\0';
  63. reverse(s);
  64. }
  65. void reverse(char s[])
  66. {
  67. if (s!=0)
  68. {
  69. int i=0;
  70. while (s[i]!=0)
  71. i++;
  72. char temp[i];
  73. for (int j=0; j<i; j++)
  74. {
  75. temp[j]=s[i-(j+1)];
  76. }
  77. for (int j=0; j<i; j++)
  78. {
  79. s[j]=temp[j];
  80. s[j+1]=0;
  81. }
  82. }
  83. }