#include <stdlib.h>
#include <stdio.h>
void itob(int n, char s[], int b);
void new_reverse(char s[]);
int main(void)
{
char buffer[10];
int iTmp, radix, flag;
while (1)
{
printf("Please input a int number(q to quit): ");
flag = scanf_s("%d", &iTmp);
if (flag != 1)
break;
printf("Please input the radix in dec num: ");
scanf_s("%d", &radix);
while (getchar() != '\n');
itob(iTmp, buffer, radix);
printf("Dec num %d in radix %d is %s\n\n", iTmp, radix, buffer);
}
system("pause");
return 0;
}
void itob(int n, char s[], int b)
{
static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, sign;
if (b < 2 || b > 36)
{
fprintf(stderr, "Can not suppoert base %d\n", b);
exit(0);
}
if ((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = digits[n % b];
} while ((n /= b) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
new_reverse(s);
}
void new_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;
}
}
转载于:https://blog.51cto.com/10738432/1706274