/******************************************************************************* * K&R 3-4 * * So the issue here is that the range that can be represented using * signed ints always has just one more on the negative side. To avoid this * an unsigned int can be used to hold the negative value. It can be extracted * from the int by obtaining the two's compliment, applying a bitwise not and * adding one. My gcc still flags this for some reason, as if -n and (~n +1) * are the same. But the output is correct. * * int to string (itoa) * * program: itoa * by.....: yetimach * date...: 5 November 2024 * * ****************************************************************************/ #include #include #define MAX 12 char gs[MAX]; /* global string */ 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; if ((sign = n) < 0) un = ~n +1; else un = n; i = 0; do { s[i++] = un % 10 + '0'; } while ((un /= 10) > 0); if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } int main(void) { printf("Enter an integer value: "); int num; scanf("%d", &num); itoa(num, gs); printf("\nThe integer has been converted to a string: %s\n", gs); return 0; }