PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Conversion

Program to convert a hexadecimal number into decimal number

Input - Output

Input
Enter a Hexadecimal number : 2A

Output
Decimal equivalent of given number : 42

Input
Enter a Hexadecimal number : 15

Output
Decimal equivalent of given number : 21

Algorithm

Step 1: START

Step 2: Take the input in hexadecimal number.

Step 3: Count the number of digits in the number.

Step 4: If n is the position of the digit from the right end then multiply each digit with the power of 16 is (n-1)

Step 5: Add all the terms after multiply and print

Step 6: END

CODE


/* Hexadecimal to Decimal Conversion */

#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
      char hexa[10];
      int decimal=0,i,j,temp,len;
      printf(" Enter the hexadecimal number : ");
      scanf("%s",hexa);
      len=strlen(hexa);
        len--;
      for(i=0;hexa[i];i++)
    {
        if(hexa[i]>='0' && hexa[i]<='9')
          temp=hexa[i]-48;
        else if(hexa[i]>='A' && hexa[i]<='F')
          temp=hexa[i]-55;
        else if(hexa[i]>='a' && hexa[i]<='f')
          temp=hexa[i]-87;
        decimal+=temp*pow(16,len);
        len--;
    }
      printf(" Decimal number of given number is = %d",decimal);
    return 0;
}


/* Hexadecimal to Decimal Conversion */

#include <iostream>
#include <math.h>
#include <cstring>
using namespace std;
int main()
{
      char hexa[10];
      int decimal=0,i,j,temp,len;
      cout<<" Enter the hexadecimal number : ";
      cin>>hexa;
      len=strlen(hexa);
        len--;
      for(i=0;hexa[i];i++)
    {
        if(hexa[i]>='0' && hexa[i]<='9')
          temp=hexa[i]-48;
        else if(hexa[i]>='A' && hexa[i]<='F')
          temp=hexa[i]-55;
        else if(hexa[i]>='a' && hexa[i]<='f')
          temp=hexa[i]-87;
        decimal+=temp*pow(16,len);
        len--;
    }
      cout<<" Decimal number of given number is = "<<decimal;
    return 0;
}

OutPut

Enter a Hexadecimal number : 2A

Decimal equivalent of given number : 42