I'm trying to a create an algorithm that can convert base 10 numbers into base n numbers, where n is at most 10. However, for some weird reason the following algorithm in C fails at certain critical points for each base. For example, for base 2 and base 3 conversions, all numbers up to and including 1023 and 52,487 work, respectively, but numbers beyond that produce some weird negative result. I can't figure out why this is happening; can anyone help me?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int returnint;
int baseconvert(int number,int base) {
if(number == 0 || base == 10) {
return returnint;
}
returnint = (number % base) + (10 * baseconvert(number / base, base));
return returnint;
}
int main() {
fprintf(stdout,"%d\n",baseconvert(1023,2));
fprintf(stdout,"%d\n",baseconvert(52487,3));
}
EDIT:
Here is the printed result of the above print statements, if that's helpful:
1410065408
-2094967296
baseconvert(1023,2)
does work in gcc andbaseconvert(52487,3)
is most likely an overflow. – Mcneelyreturn
in yourmain()
function. – Ventriloquizebaseconvert(1023,2)
andbaseconvert(52487,3)
work; those are posted as examples of the highest values that work. I tried using a larger integer, as I commented below on Mark Wilkin's post, but that didn't work. – Crispationint
variable is the count, for example, the amount of apples in a bag. Regardless of how you represent it in different bases, there are fixed amount of apples in that bag, and that fixed amount is to be held within theint
. Base should only matter while outputting the value. For example:int n = 20; printf( "%d %x %o", n, n, n );
will outputn
as20
,14
and24
. – Choirboy