Friday, 20 June 2014

C++ program to convert hexadecimal to decimal number

Here is a C++ program to convert hexadecimal to decimal. Here are the different methods to convert hexadecimal to decimal like using recursion,manipulators etc.
How to convert hexadecimal to decimal.


Method 1 : C++ program to convert hexadecimal to decimal
#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
int main()
{
    long i,decimal=0,hexa[20];
    char input[20];
    cout<<"Enter the number in Hexadecimal ";
    gets(input);
    for(i=0;input[i]!='\0';i++)
    {
        if(input[i]>='A')
            hexa[i]=input[i]-55;
        else if(input[i]>='a')
            hexa[i]=input[i]-87;
        else
            hexa[i]=input[i]-48;
    }
    --i;
    cout<<"Decimal equivalent : ";
    for(int y=0;i>=0;y++,i--)
             decimal+=hexa[i]*pow(16,y);
    cout<<decimal;
    return 0;
}


Method 2 : C++ program to convert hexadecimal to decimal using recursion
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int deci(char *str,int i,int j)
{
    int mul;
    if(i<0)
        return 0;
    if(str[i]>=65&&str[i]<=70)
        mul=str[i]-55;
    else if(str[i]>=97)
        mul=str[i]-87;
    else
        mul=str[i]-48;
    return mul*pow(16,j)+deci(str,i-1,j+1);
}
int main()
{
    char str[10];
    cout<<"Enter Hexadecimal number : ";
    cin>>str;
    cout<<"Decimal equivalent : "<<deci(str,strlen(str)-1,0);
    return 0;
}




Method 3 : Another C++ program to convert hexadecimal to decimal
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
    int decimal=0,lt;
    char num[30];
    cout<<"Enter the number in Hexadecimal ";
    cin>>num;
    lt=strlen(num)-1;
    for(int i=lt;i>=0;i--)
        decimal+=(num[i]-48)*pow(16,lt-i);
    cout<<"Decimal equivalent "<<decimal;
    return 0;
}



Method 4 : C++ program to convert hexadecimal to decimal using function
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
void hex(char *a,int lt)
{
    int decimal=0;
    for(int i=lt;i>=0;i--)
        decimal+=(a[i]-48)*pow(16,lt-i);
    cout<<"Decimal equivalent "<<decimal;
}
int main()
{
    int lt;
    char num[30];
    cout<<"Enter the number in hexadecimal ";
    cin>>num;
    lt=strlen(num)-1;
    hex(num,lt);
    return 0;
}




Method 5 : C++ program to convert hexadecimal to decimal using manipulators
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
    cout<<"Decimal equivalent of hexadecimal number 6A is : "<<dec<<0x6A;
    return 0;
}

No comments:

Post a Comment