Powered By Blogger

Wednesday, 14 December 2011

convert decimal number to hexadecimal in c programming


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include "stack.h"
  5.  
  6. int main(void)
  7. {
  8. int num;
  9. char alpha;
  10. int* digit;
  11. STACK* stack;
  12.  
  13. stack = createStack ();
  14.  
  15. printf("Please enter your integer (decimal): \n");
  16. scanf("%d" , &num);
  17.  
  18. while(num > 0)
  19. {
  20. digit = (int*) malloc (sizeof(int));
  21. *digit = num % 16;
  22. push (stack, digit);
  23. num = num/16;
  24. }
  25.  
  26. while (!emptyStack (stack))
  27. {
  28. digit = (int*)popStack (stack);
  29.  
  30. if(*digit > 9)
  31. {
  32. if(*digit == 10)
  33. alpha = 'A';
  34. else if(*digit == 11)
  35. alpha = 'B';
  36. else if(*digit == 12)
  37. alpha = 'C';
  38. else if (*digit == 13)
  39. alpha = 'D';
  40. else if (*digit == 14)
  41. alpha = 'E';
  42. else if (*digit == 15)
  43. alpha = 'F';
  44. }
  45.  
  46. printf("%c", alpha);
  47.  
  48. else
  49. printf("%d", digit);
  50. }
  51.  
  52. destroyStack(stack);
  53. return 0;
  54. }