exc/k&r/03-control-flow/03-05.c

54 lines
1.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <string.h>
void itob(int n, char *s, unsigned b);
/* passes args to itob, n defaults to INT_MIN, base defaults to 10 */
int main(int argc, char *argv[])
{
int n, b;
n = (argc > 1) ? atoi(argv[1]) : INT_MIN;
b = (argc > 2) ? atoi(argv[2]) : 10;
if (b <= 0) {
printf("error : invalid base %d\n", b);
return 1;
}
char s[(int)log10(INT_MAX) + 3]; /* +3 for sign and \0 */
itob(n, s, b);
printf("%s\n", s);
return 0;
}
void reverse(char *s);
/* itob: converts int n to string in base b and writes it to s */
void itob(int n, char *s, unsigned b)
{
unsigned un;
if (n < 0) {
un = -n;
*(s++) = '-';
} else
un = n;
char d, *sc = s;
do {
d = un % b;
*(sc++) = d + ((d > 9) ? 'a' - 10 : '0');
} while ((un /= b) > 0);
*sc = '\0';
reverse(s);
}
/* reverse: reverses string s in place */
void reverse(char *s)
{
char c, *s2;
for (s2 = s + strlen(s) - 1; s < s2; s++, s2--)
c = *s, *s = *s2, *s2 = c;
}