Decimal to Base 2 - 16 Conversion

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is offline Offline Dec 1st, 2004, 2:42 pm |
0
Let's expand the decimal to binary converter to include, amongst others, octal and hexadecimal conversions. Also shows how to exert some input control. Simple stuff!
Quick reply to this message  
C Syntax
  1. // Convert a positive decimal integer to a number of base (2 to 16)
  2. // Also a good example for using do ... while() to check input
  3. // tested with Pelles C vegaseat 1dec2004
  4.  
  5. #include <stdio.h>
  6.  
  7. char *conv_base(long number, int base);
  8.  
  9. int main()
  10. {
  11. int base;
  12. long number;
  13. char yn;
  14.  
  15. do
  16. {
  17. do
  18. {
  19. printf("\n\nEnter an integer number : ");
  20. scanf("%ld",&number);
  21. } while (number < 1); // positive integers only
  22. do
  23. {
  24. printf("\nEnter the base (2-16) : ");
  25. scanf("%d",&base);
  26. } while (base < 2 || base > 16); // stay in range
  27.  
  28. printf("\nThe converted number is : %s",conv_base(number,base));
  29. printf("\n\n Any more (y/n) : ");
  30. getchar(); // a little goofy but needed
  31. yn = getchar();
  32. } while (!(yn == 'n' || yn == 'N'));
  33.  
  34. return 0;
  35. }
  36.  
  37. char *conv_base(long number, int base)
  38. {
  39. long remain;
  40. int n = 0, k = 0;
  41. static char temp[32], result[32];
  42. static char *digit = "0123456789ABCDEF"; // list of digits
  43.  
  44. do
  45. {
  46. remain = number % base; // modulo gets remainder
  47. number = number / base; // whittle down number
  48. temp[k++] = digit[remain];
  49. } while (number > 0);
  50.  
  51. while (k >= 0)
  52. {
  53. result[n++] = temp[--k]; // spell forward
  54. }
  55.  
  56. result[n-1] = 0; // add string EOS
  57. return (result);
  58. }
  59.  

Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC