fork download
  1. #include <stdio.h>
  2.  
  3. typedef enum
  4. {
  5. BASE_DECIMAL = 10,
  6. BASE_HEXADECIMAL = 16,
  7. BASE_BINARY = 2,
  8. BASE_ENUM_COUNT = 3
  9. } Bases;
  10.  
  11. int Pow(int x, int exponent) // TODO: should this be inline?
  12. {
  13. int base_num = x;
  14.  
  15. if(exponent)
  16. {
  17. for(int i = 1; i < exponent; i++)
  18. {
  19. x = x * base_num;
  20. }
  21. return x;
  22. }
  23. else
  24. {
  25. return 1;
  26. }
  27. }
  28.  
  29. void
  30. IntToAscii(char *output_buffer, const int number, const Bases base) {
  31. int num = number;
  32. int temp_num = 0;
  33. int digit = 0;
  34. int total_digits = 0;
  35. int divisor = 0;
  36.  
  37. if (num == 0)
  38. {
  39. *output_buffer = '0';
  40. return;
  41. } else if(num < 0)
  42. {
  43. *output_buffer = '-';
  44. output_buffer++;
  45. num = num * -1;
  46. }
  47.  
  48. temp_num = num;
  49. while (temp_num > 0) {
  50. temp_num = temp_num / base;
  51. total_digits++;
  52. }
  53.  
  54. total_digits = total_digits - 1;
  55.  
  56. for (int x = total_digits; x >= 0; x--)
  57. {
  58. divisor = Pow(base, x);
  59. digit = num / divisor;
  60. if(digit < 10 || base == BASE_DECIMAL)
  61. {
  62. *output_buffer = (char)(digit + '0');
  63. }
  64. else if(base == BASE_HEXADECIMAL)
  65. {
  66. digit = digit - 10;
  67. *output_buffer = (char)(digit + 'A');
  68. }
  69.  
  70. num = num - (digit * divisor);
  71.  
  72. output_buffer++;
  73. }
  74. }
  75.  
  76.  
  77. int main()
  78. {
  79. char text[256] = {};
  80. IntToAscii(text, 0x5eadbeef, BASE_HEXADECIMAL);
  81. printf("%s\n", text);
  82. }
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
Success #stdin #stdout 0s 5280KB
stdin
45
stdout
5E������