0

So im having trouble with creating a recursive function to convert a number from bases 2-10 to bases 2-16. I need it to return a string (obviously , due to the bases greater than 10).

here is my function:

main would call it like:

answer = baseConversion(101, 10, 2);

I have hex as a constant char:

const char Hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

char * baseConverter(int number,int currbase, int base){

    if(currbase != 10){

        number = base10Converter(number, currbase);  //converts the number to base of 10 

        currbase = 10;
    }

    if(number == 0 || base==10){

        return number;

    }

    int r = number%base;

    printf("%c", Hex[r]);

    //return (number % base) + 10*baseConverter(number /base, currbase, base); // this gives the answer as an integer.
    return Hex[r]+ && baseConverter(number /base, currbase, base) // I dont know what to add here to add the characters together 
}

i need help with my return statement and recursive call. Do i need to declare a char array within the function and then append the chars i get from hex[r] to it? If so, How do i go about doing that because I cant change the parameters

1 Answers1

2
  • ints done't have bases, they just have values. How you display, or represent with a string, have bases. Thus, it doesn't make sense to have a currBase, unless you started with a string representation of the value you want to convert.
  • baseConverter, is defined so that it returns a string; since it is not passed space for that string, it will have to allocate it.
  • Thus, for the recursive case, you'd call baseConverter to give you a string for the rest of the number, and use that to make a new string (which you need to allocate), being sure to deallocate the string you got from the recursive call when you are done.
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Thanks for the reply. For your third point you mentioned i had to allocate memory for a sting in my function (baseConverter). However i was wondering if i returned strncmp(hex[r], baseConverter(...)); would that work? if not how would i go about doing it your way. @Scott Hunter – mrquiksilver Oct 19 '14 at 20:55
  • strcat(hax[r], baseConverter(...)); i mean – mrquiksilver Oct 19 '14 at 21:15
  • `strcat` needs a string to concatenate to, which means that string needs to be allocated at some point. Also, it assumes that you have allocated enough space for the concatenation. Finally, `strcat` requires you concatenate a string, not a character. – Scott Hunter Oct 20 '14 at 00:32