Posted By

rtperson on 12/02/12


Tagged


Versions (?)

Radix Conversion In C


 / Published in: C
 

How to convert an integer from base 10 to a string of base x (where x <= 20). The #define RESERVE_CHARS should be set to the largest size for the resulting string. Or feel free to adjust the code to reallocate storage for the string.

  1. char* convertFromDecimal(int num, int toBase) {
  2. char chars[] = { "0123456789ABCDEFGHIJ" };
  3. char *result;
  4. char digit[] = { '\0', '\0' };
  5. char temp[RESERVE_CHARS];
  6. memset(temp, 0, sizeof temp);
  7. result = (char*)calloc(RESERVE_CHARS, sizeof(char));
  8. memset(result, 0, sizeof result);
  9.  
  10. int over;
  11. while (num > 0) {
  12. over = num % toBase;
  13. digit[0] = chars[over];
  14. strcat(temp, digit);
  15. num /= toBase;
  16. }
  17.  
  18. /* reverse the temp string to get real digit */
  19. int p, x;
  20. for ( p = strlen(temp)-1, x=0; p >= 0; --p, ++x) {
  21. result[x] = temp[p];
  22. }
  23.  
  24. return result;
  25. }

Report this snippet  

You need to login to post a comment.