fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int convertBase(unsigned long n, unsigned base,
  5. char *dst, size_t dlen)
  6. {
  7. static const char alpha[] = "0123456789abcdef";
  8. char *p = dst, *q = dst;
  9.  
  10. // invalid base filter
  11. if (base == 1 || base >= sizeof(alpha) || dlen < 1)
  12. return -1;
  13.  
  14. // conversion
  15. while (p-dst < dlen-1)
  16. {
  17. *p++ = alpha[ n % base ];
  18. if ((n /= base) == 0)
  19. break;
  20. }
  21.  
  22. // ran out of space?
  23. if (n)
  24. return -1;
  25.  
  26. // terminate and reverse
  27. *p = 0;
  28. while (q < p--)
  29. {
  30. char c = *q;
  31. *q++ = *p;
  32. *p = c;
  33. }
  34. return 0;
  35. }
  36.  
  37. int main(void)
  38. {
  39. unsigned long int n = 1000000000U;
  40. char buff[65];
  41.  
  42. for (unsigned int i=2; i<=16; ++i)
  43. {
  44. printf("%lu in Base %u = ", n, i);
  45. if (convertBase(n, i, buff, sizeof(buff)) == 0)
  46. puts(buff);
  47. }
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
1000000000 in Base 2 = 111011100110101100101000000000
1000000000 in Base 3 = 2120200200021010001
1000000000 in Base 4 = 323212230220000
1000000000 in Base 5 = 4022000000000
1000000000 in Base 6 = 243121245344
1000000000 in Base 7 = 33531600616
1000000000 in Base 8 = 7346545000
1000000000 in Base 9 = 2520607101
1000000000 in Base 10 = 1000000000
1000000000 in Base 11 = 47352388a
1000000000 in Base 12 = 23aa93854
1000000000 in Base 13 = 12c23a19c
1000000000 in Base 14 = 96b4b6b6
1000000000 in Base 15 = 5cbd146a
1000000000 in Base 16 = 3b9aca00