Created
November 12, 2009 06:12
-
-
Save shaobin0604/232645 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 -(2^wordsize - 1). Explain why not. Modify it to print that value | |
* correctly, regardless of the machine on which it runs. | |
*/ | |
#include <stdio.h> | |
#include <limits.h> | |
#include <string.h> | |
#define abs(x) ((x) < 0 ? -(x) : (x)) | |
void reverse(char s[]) | |
{ | |
int i, j, c; | |
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; | |
sign = n; | |
i = 0; | |
do { | |
s[i++] = abs(n % 10) + '0'; | |
} while ((n /= 10) != 0); | |
if (sign < 0) | |
s[i++] = '-'; | |
s[i] = '\0'; | |
reverse(s); | |
} | |
int main(void) | |
{ | |
char s[20]; | |
printf("INT_MIN = %d\n", INT_MIN); | |
itoa(INT_MIN, s); | |
printf("INT_MIN = %s\n", s); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment