1 Replies - 461 Views - Last Post: 07 March 2009 - 10:23 PM Rate Topic: -----

#1 AmitTheInfinity   User is offline

  • C Surfing ∞
  • member icon

Reputation: 119
  • View blog
  • Posts: 1,565
  • Joined: 25-January 07

Converting Decimal To other base up to 16

Posted 07 February 2007 - 03:09 AM

Description: Converts Decimal to Other Bases from 2 to 16 and displays it.
[Both Iterative And Recursive]
#include <stdio.h>

void convertToBase(int, int);
void convertToBaseRec(int, int);
int main()
{
     int base,number;
     // the number to be converted
     printf("Enter The Number : ");
     scanf("%d",&number);
     // accept only valid based that is from 2 to 16
     while(base>16 || base<2)
     {
          printf("Enter The Base : ");
          scanf("%d",&base);
     }
     //iterative
      printf("n Output Of Iterative Conversion : ");
     convertToBase(base,number);
      //recursion
      printf("n Output Of Recursive Conversion : ");
     convertToBaseRec(base,number);

     return 0;
}

//convert and print the answer

void convertToBase(int base, int number)
{
     //this array contains all digits that are used in different bases til 16 [hex]
     char digits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
     char output[100];
     int i=0;
     //actual logic
     while(number>0)
     {
          //copy character from array digit situated at index = reminder of number / base
          output[i++] = digits[number%base];     
          number = number/base;
     }
     i--;
     //print output
     for(;i>=0;i--)
     {
          printf("%c",output[i]);
     }
}

void convertToBaseRec(int base, int number)
{
    //this array contains all digits that are used in different bases til 16 [hex]
     char digits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
     //actual logic
     if(number<=0)
     {
          return;
     }
     //Call Recursively
     convertToBaseRec(base,number/base);
     //print character from array digit situated at index = reminder of number / base
     printf("%c",digits[number%base]);     
     
}


Is This A Good Question/Topic? 0
  • +

Replies To: Converting Decimal To other base up to 16

#2 npsnet   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 07-March 09

Re: Converting Decimal To other base up to 16

Posted 07 March 2009 - 10:23 PM

Is there any C code snippet which will directly convert Binary format string to Hexadecimal string ? plz let me know
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1