This is a C++ Program to Convert a Given Hexadecimal Number to its Decimal Equivalent.
Problem Description
The program takes a hexadecimal number and converts it into its decimal equivalent.
Problem Solution
1. The program takes a hexadecimal number.
2. Its length is stored in a variable using a string function.
3. Using a for loop, every character is converted to its decimal equivalent by multiplying with powers of 16.
4. The result is printed.
5. Exit.
C++ Program/Source code
Here is the source code of C++ Program to Convert a Given Hexadecimal Number to its Decimal Equivalent. The program output is shown below.
#include
#include
#include
using namespace std;
int main ()
{
char num[20];
int i, r, len, hex = 0;
cout << "Enter a hexadecimal number : ";
cin >> num;
len = strlen(num);
for (i = 0; num[i] != ‘\0’; i++)
{
len–;
if(num[i] >= ‘0’ && num[i] <= '9')
r = num[i] - 48;
else if(num[i] >= ‘a’ && num[i] <= 'f')
r = num[i] - 87;
else if(num[i] >= ‘A’ && num[i] <= 'F')
r = num[i] - 55;
hex += r * pow(16,len);
}
cout << "\nDecimal equivalent of " << num << " is : " << hex;
return 0;
}
Runtime Test Cases
Case 1 :
Enter a hexadecimal number : f
Decimal equivalent of f is : 15
Case 2 :
Enter a hexadecimal number : 74
Decimal equivalent of 74 is : 116
Case 3 :
Enter a hexadecimal number : DEF
Decimal equivalent of DEF is : 3567