codescracker
c++

C++ Program to Convert Hexadecimal to Decimal



« Previous Program Next Program »

In this article, you will learn and get code on hexadecimal to decimal conversion in C++. Here are the list of programs, you will go through:

Before going through these programs, if you're not aware about some simple steps and formula used for the conversion, then you can refer to hexadecimal to decimal to get every required things.

Hexadecimal to Decimal in C++

To convert a number from hexadecimal to decimal in C++ programming, you have to ask from user to enter the hexadecimal number first. And then convert it into its equivalent decimal value. as shown in the program given below.

The question is, write a program in C++ that converts hexadecimal number to decimal number. Here is its answer:

// C++ Program to Convert Hexadecimal to Decimal
// ----codescracker.com----

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int decimalNum=0, rem, i=0, len=0;
    char hexDecNum[20];
    cout<<"Enter the Hexadecimal Number: ";
    cin>>hexDecNum;
    while(hexDecNum[i]!='\0')
    {
        len++;
        i++;
    }
    len--;
    i=0;
    while(len>=0)
    {
        rem = hexDecNum[len];
        if(rem>=48 && rem<=57)
            rem = rem-48;
        else if(rem>=65 && rem<=70)
            rem = rem-55;
        else if(rem>=97 && rem<=102)
            rem = rem-87;
        else
        {
            cout<<"\nInvalid Hex Digit!";
            cout<<endl;
            return 0;
        }
        decimalNum = decimalNum + (rem*pow(16, i));
        len--;
        i++;
    }
    cout<<"\nEquivalent Decimal Value: "<<decimalNum;
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

C++ program convert hexadecimal to decimal

Now supply any hexadecimal number input say 1D7F and press ENTER key to convert and prints its equivalent decimal value as shown in the snapshot given below:

hexadecimal to decimal c++

Program doesn't cares about the case of alphabet A-F (hex characters corresponds to hex digits 10 to 15). That is, either entered in lowercase or in uppercase as shown in the output given below:

hexadecimal to decimal conversion c++

The dry run of above program with hexadecimal number input 1D7F goes like:

You can also compare and process directly with the character of hexDecNum[] one by one. To do this, replace the following block of code:

if(rem>=48 && rem<=57)
    rem = rem-48;
else if(rem>=65 && rem<=70)
    rem = rem-55;
else if(rem>=97 && rem<=102)

with the block of code given below:

if(rem>='0' && rem<='9')
    rem = rem-48;
else if(rem>='A' && rem<='F')
    rem = rem-55;
else if(rem>='a' && rem<='f')

Without using pow() Function

If you don't want to use pow() function of math.h header file, then you can replace the following statement:

decimalNum = decimalNum + (rem*pow(16, i));

with

k=1;
mul=1;
while(k<=i)
{
    mul=16*mul;
    k++;
}
decimalNum = decimalNum + (rem*mul);

Note - Don't forgot to declare both new variables k and mul at start of the program. And remove the header file, math.h. Rest of the things will be same.

What if Hexadecimal Number contains Fractional Part ?

To deal with a type of input that contains fractional part. That is a hexadecimal number containing fractional part (or decimal point), use the following program:

// C++ Convert Hexadecimal (including decimal point) to Decimal
// ----codescracker.com----

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int decimalNum=0, decNumOne=0, dotPosition=0;
    int rem, i=0, len=0, lenTemp;
    float decNumTwo=0;
    char hexDecNum[20];
    cout<<"Enter the Hexadecimal Number: ";
    cin>>hexDecNum;
    while(hexDecNum[i]!='\0')
    {
        if(hexDecNum[i]=='.')
            dotPosition = i;
        len++;
        i++;
    }
    len--;
    i=0;
    if(dotPosition==0)
    {
        while(len>=0)
        {
            rem = hexDecNum[len];
            if(rem>=48 && rem<=57)
                rem = rem-48;
            else if(rem>=65 && rem<=70)
                rem = rem-55;
            else if(rem>=97 && rem<=102)
                rem = rem-87;
            else
            {
                cout<<"\nInvalid Hex Digit!";
                cout<<endl;
                return 0;
            }
            decimalNum = decimalNum + (rem*pow(16, i));
            len--;
            i++;
        }
        cout<<"\nEquivalent Decimal Value: "<<decimalNum;
    }
    else
    {
        lenTemp = dotPosition-1;
        while(lenTemp>=0)
        {
            rem = hexDecNum[lenTemp];
            if(rem>=48 && rem<=57)
                rem = rem-48;
            else if(rem>=65 && rem<=70)
                rem = rem-55;
            else if(rem>=97 && rem<=102)
                rem = rem-87;
            else
            {
                cout<<"\nInvalid Hex Digit!";
                cout<<endl;
                return 0;
            }
            decNumOne = decNumOne + (rem*pow(16, i));
            lenTemp--;
            i++;
        }
        lenTemp = dotPosition+1;
        i=-1;
        while(lenTemp<=len)
        {
            rem = hexDecNum[lenTemp];
            if(rem>=48 && rem<=57)
                rem = rem-48;
            else if(rem>=65 && rem<=70)
                rem = rem-55;
            else if(rem>=97 && rem<=102)
                rem = rem-87;
            else
            {
                cout<<"\nInvalid Hex Digit!";
                cout<<endl;
                return 0;
            }
            decNumTwo = decNumTwo + (rem*pow(16, i));
            lenTemp++;
            i--;
        }
        decNumTwo = decNumOne+decNumTwo;
        cout<<"\nEquivalent Decimal Value: "<<decNumTwo;
    }
    cout<<endl;
    return 0;
}

Here is its sample run with hexadecimal number input as 5A9.63

hexadecimal with decimal to decimal c++

The variable dotPosition is used here, that checks whether decimal point is available in the hexadecimal input or not. If hexadecimal input contains fractional part (or has decimal point), then 1 gets initialized to dotPosition variable. Checks later, whether its value is equal to 0 or not. If it is equal to 0 (means 1 does not gets initialized to it), then process the normal conversion, otherwise deal with different rules as shown in above program.

That is, if a hexadecimal number contains fractional part (or decimal point), then we've used two part. One before decimal and one after decimal.

The part that is available before decimal, gets converted into its equivalent decimal value and initialized to decNumOne. Whereas the part that is available after decimal, gets converted into its equivalent decimal value and initialized to decNumTwo (float type variable). Finally add and print the value.

Note - The rules to convert hexadecimal (after decimal point) to decimal is already discussed in the article of Hexadecimal (with Fractional) to Descimal.

Using Function and Pointer

This program uses function and pointer to convert hexadecimal to decimal in C++.

// ----codescracker.com----

#include<iostream>
#include<math.h>
using namespace std;
unsigned long HexDecToDec(char []);
int main()
{
    unsigned long decimalNum;
    char hexDecNum[10];
    cout<<"Enter the Hexadecimal Number: ";
    cin>>hexDecNum;
    decimalNum = HexDecToDec(hexDecNum);
    if(decimalNum==0)
        cout<<"\nInvalid Hex Digit!";
    else
        cout<<"\nEquivalent Decimal Value: "<<decimalNum;
    cout<<endl;
    return 0;
}
unsigned long HexDecToDec(char hexDecNum[])
{
    char *hexDecPointer;
    int i, len = 0;
    const int base = 16;
    unsigned long decimalNum = 0;
    // Find the len of Hexadecimal Number
    for(hexDecPointer=hexDecNum; *hexDecPointer != '\0'; hexDecPointer++)
        len++;
    // Again initialize the starting address of Hexadecimal Number
    hexDecPointer = hexDecNum;
    // Now convert hex digit to decimal number one by one
    for(i=0; *hexDecPointer != '\0' || i<len; i++, hexDecPointer++)
    {
        if(*hexDecPointer>=48 && *hexDecPointer<=57)
            decimalNum = decimalNum + (*hexDecPointer - 48)*pow(base, len-i-1);
        else if(*hexDecPointer>=65 && *hexDecPointer<=70)
            decimalNum = decimalNum + (*hexDecPointer - 55)*pow(base, len-i-1);
        else if(*hexDecPointer>=97 && *hexDecPointer<=102)
            decimalNum = decimalNum + (*hexDecPointer - 87)*pow(base, len-i-1);
        else
            len=0;
    }
    if(len==0)
        return 0;
    else
        return decimalNum;
}

Note - This program doesn't work with hexadecimal input containing fractional (decimal) part.

To create the program using user-defined function that converts hexadecimal (with fractional part) to its equivalent decimal value. Then you can use the program that I've already mentioned above to deal with this type of input. Just alter it and create with yourself.

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker