Hexadecimal to Decimal Conversion
“Hexadecimal to Decimal Conversion” is one of the classic programming problem exercise. Here, we are given a hexadecimal number, entered by user and our task is to write a program to convert the hexadecimal number to its equivalent decimal number.
Hexadecimal Numbers uses 16 values to represent the number. Numbers from 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A – F.
Examples (Hexadecimal to Decimal Conversion):
Hexadecimal = A Decimal = 15 Hexadecimal = 4E Decimal = 78
The steps required to convert hexadecimal number into decimal number are as follows:
- Take Iterator = 1 and Decimal = 0.
- Read the given hexadecimal string in reverse order character by character.
- If the character encountered is digit between 0 to 9, then convert it into number by subtracting 48 from it and store the result into temp.
- Else, if the character encountered is between ‘A’ to ‘F’, then convert it into number by subtracting 55 from it and store the result into temp.
- Decimal = Decimal + temp*iterator.
- Multiply the iterator by 16.
- Repeat the steps from 2 to 6 for all the characters of the hexadecimal string.
- Print the result.
C++ Program for Hexadecimal to Decimal Conversion is as follows:
/* C++ Program for Hexadecimal to Decimal Conversion */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan the Hexadecimal Number */
string Hexadecimal;
cout<<"Enter the Hexadecimal Number: ";
cin>>Hexadecimal;
/* Converting Hexadecimal to Decimal*/
int Decimal = 0;
int iterator = 1;
int size = Hexadecimal.length();
for(int i = size - 1; i >= 0; i--)
{
int temp;
if(Hexadecimal[i]>='A' && Hexadecimal[i]<='F')
{
temp = Hexadecimal[i] - 55;
}
else
{
temp = Hexadecimal[i] - 48;
}
Decimal = Decimal + temp*iterator;
iterator = iterator * 16;
}
/*Printing the result */
cout<<"The Decimal of "<<Hexadecimal<<" is "<<Decimal;
}
OUTPUT: Enter the Hexadecimal Number: 4E The Decimal of 4E is 78
Related Posts:
- Program to convert hexadecimal number to binary number.
- Program to convert hexadecimal number to octal number.
- Program to convert binary number to octal number.
- Program to convert binary number to decimal number.
- Program to convert binary number to hexadecimal number.
- Program to convert octal number to binary number.
- Program to convert octal number to decimal number.
- Program to convert octal number to hexadecimal number.
- Program to convert decimal number to binary number.
- Program to convert decimal number to octal number.
- Program to convert decimal number to hexadecimal number.
- Program to print Fibonacci Series up to Nth Term.
- Program to find and print nth Fibonacci number.
- Program to find Power of the Number.
- Program to find Quotient and Remainder.
- Program to find largest amongst three numbers.
- Program to find factorial of a number.
- Program to find GCD of two numbers.
- Program to find LCM of two numbers.
- Program to check whether entered number is odd or even.