Decimal to Base 2 - 16 Conversion

vegaseat 1 Tallied Votes 176 Views Share

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!

// Convert a positive decimal integer to a number of base (2 to 16)
// Also a good example for using do ... while() to check input
// tested with Pelles C     vegaseat     1dec2004

#include <stdio.h>

char *conv_base(long number, int base);

int main()
{
  int  base;
  long number;
  char yn;

  do 
  {
    do 
    {
      printf("\n\nEnter an integer number :  ");
      scanf("%ld",&number);
    } while (number < 1);  // positive integers only
    do 
    {
      printf("\nEnter the base (2-16)   :  ");
      scanf("%d",&base);
    } while (base < 2 || base > 16); // stay in range
    
    printf("\nThe converted number is :  %s",conv_base(number,base));
    printf("\n\n         Any more (y/n) : ");
    getchar();       // a little goofy but needed
    yn = getchar();
  } while (!(yn == 'n' || yn == 'N'));
  
  return 0;
}

char *conv_base(long number, int base)
{
  long remain;
  int  n = 0, k = 0;
  static char temp[32], result[32];
  static char *digit = "0123456789ABCDEF"; // list of digits

  do 
  {
    remain = number % base;    // modulo gets remainder
    number = number / base;    // whittle down number
    temp[k++] = digit[remain];
  } while (number > 0);
  
  while (k >= 0)
  {
    result[n++] = temp[--k];   // spell forward
  }
    
  result[n-1] = 0;             // add string EOS
  return (result);
}