This is a C++ Program to Convert a Given Hexadecimal Number to its Decimal Equivalent.
The program takes a hexadecimal number and converts it into its decimal equivalent.
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.
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<iostream>
#include<string.h>
#include<math.h>
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;
}
1. The user is asked to enter a hexadecimal number and its value is stored in the character variable ‘num’.
2. The variable ‘hex’ is initialized as 0 and the length of num is stored in the variable ‘len’.
3. Using a for loop, len is decremented and every character is checked.
4. If it lies between 0 to 9, 48 is subtracted from the ASCII value and stored in r.
5. Else if it lies between ‘a’ to ‘f’, 87 is subtracted, else 55 is subtracted.
6. r is multiplied with 16 power len and stored in hex.
7. The loop continues till the string reaches the end or null character is encountered.
8. The result is then printed.
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
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Check Computer Science Books
- Check C++ Books
- Practice Programming MCQs
- Practice Computer Science MCQs
- Apply for C++ Internship