Pages

This blog is under construction

Wednesday, December 12, 2018

C program to convert Hexadecimal number to Decimal number system

Example  (AB31C)16  =(?)10

Solution:



=AB31C
=AX164 +BX163 +3X162 + 1X161 +CX160
=10X164 +11X163 +3X162 + 1X161 +12X160
=10X164 +11X163 +3X162 + 1X161 +12X160
=10X65536 +11X4096 +3X256 +1X16 +12X1
=655360+45056+768 +16+12
=701212

C Program:

#include<stdio.h>
#include<string.h>
#include<math.h>
void main()
{ char str[10];
    int a,i,b[10],flag=0,s=0,p=0;
   printf("\nEnter a hexadecimal number");
   gets(str);
   for(i=0;i<strlen(str);i++)
         {  switch(str[i])
     {  case '0': b[i]=0;break;
case '1':b[i]=1;break;
case '2':b[i]=2;break;
case '3':b[i]=3;break;
case '4':b[i]=4;break;
case '5':b[i]=5;break;
case '6':b[i]=6;break;
case '7':b[i]=7;break;
case '8':b[i]=8;break;
case '9':b[i]=9;break;
case 'A': b[i]=10;break;
case 'B':b[i]=11;break;
case 'C':b[i]=12;break;
case 'D':b[i]=13;break;
case 'E':b[i]=14;break;
case 'F':b[i]=15;break;
default:
  flag=1; break;
  }
      }
       if(flag==0)
         {     for(--i;i>=0;i--)
           {  s=s+b[i]*pow(16,p);
               p++;
           }
           printf("\nEquivalent decimal no. is=%d",s);
       }
    else
      printf("\nwrong input");
}

Output:

Enter a hexadecimal number AB31C                                                                                                                   
Equivalent decimal no. is=701212



No comments:

Post a Comment