Converting base 10 to base 3...
Michael J. Steiner
U23405 at UICVM
Thu Sep 1 10:04:41 AEST 1988
I happen to have a program that can convert a base-10 number to any base
between 2 and 16. Here is the code:
#include <stdio.h>
main()
{
int base, j;
char s[20];
char *gets();
void cvt();
printf("Enter a number base:\n");
base = atoi(gets(s));
printf("Enter a number:\n");
j = atoi(gets(s));
cvt(j, base);
}
/***
Function to convert base 10 number to another base within the
range of base 2 through base 16. The function displays the
conversion as part of the function.
Argument list: int value the value to convert
int base the base used
Return value: nothing useful returned from function
***/
void cvt(value, base)
int value, base;
{
int i = 0;
static char vals[] = "0123456789abcdef";
char c[20];
do {
c[i++] = vals[value % base];
} while ((value /= base) != 0);
while (i--)
putchar(c[i]);
}
That's all of it. Since the program is quite simple, you can probably deduce
the algorithm from it. Hope this helps.
Michael Steiner
Email: U23405 at UICVM.BITNET
More information about the Comp.lang.c
mailing list