Radix Conversion In C


/ Published in: C
Save to your folder(s)

How to convert an integer from base 10 to a string of base x (where x


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.