Advertisement
cd62131

Radix Conversion from Ruby

Nov 21st, 2013
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. const char digitmap[] = "0123456789abcdef";
  5.  
  6. char *num_to_s(int val, int base) {
  7.   char *ret = (char *)malloc(sizeof(char) * 255);
  8.   ret = ret + 255;
  9.   *--ret = '\0';
  10.   do {
  11.     *--ret = digitmap[(int )(val % base)];
  12.   } while (val /= base);
  13.   return ret;
  14. }
  15.  
  16. int main(int argc, char **argv) {
  17.   int n = 1424;
  18.   printf("base 2: %s\n", num_to_s(n, 2));
  19.   printf("base 4: %s\n", num_to_s(n, 4));
  20.   printf("base 8: %s\n", num_to_s(n, 8));
  21.   printf("base 16: %s\n", num_to_s(n, 16));
  22.   return EXIT_SUCCESS;
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement