Home »
C++ Programs
C++ program to convert hexadecimal to decimal number using class
Submitted by Shubh Pachori, on August 25, 2022
Problem statement
Given a hexadecimal value, we have to convert it into using the class and object approach.
Example:
Input:
Enter Hexadecimal: FFFF
Output:
Decimal Number: 65535
C++ code to convert hexadecimal to decimal number using the class and object approach
#include <iostream>
#include<math.h>
using namespace std;
// create a class
class HexaToDecimal {
// private data member
private:
char hexa[20];
// public functions
public:
// getHexa() function to get the hexadecimal
void getHexa() {
cout << "Enter HexaDecimal:";
cin >> hexa;
}
// HToD() function to convert hexadecimal to decimal
int HToD() {
// initialising int type variables for operations
int index, length, base = 1, decimal = 0;
// for loop to find out the length of the hexa
for (length = 0; hexa[length]; length++);
// for loop to convert hexadecimal to decimal
for (index = length - 1; index >= 0; index--) {
// if condition to check if the character
// at index in hexa is a digit
if (hexa[index] >= '0' && hexa[index] <= '9') {
// multiply base into character at index of
// hexa after subtracting 48 from it and
// add it to decimal
decimal = decimal + (hexa[index] - 48) * base;
// multiply base with 16
base = base * 16;
}
// if condition to check if the character at index in
// hexa is a uppercase character from A to F
else if (hexa[index] >= 'A' && hexa[index] <= 'F') {
// multiply base into character at index of
// hexa after subtracting 55 from it and
// add it to decimal
decimal = decimal + (hexa[index] - 55) * base;
// multiply base with 16
base = base * 16;
}
}
// returning decimal number
return decimal;
}
};
int main() {
// create an object
HexaToDecimal H;
// int type variable to store decimal number
int decimal;
// function is called by the object to get hexadecimal
H.getHexa();
// HToD() function to convert hexadecimal to decimal
decimal = H.HToD();
cout << "Decimal Number: " << decimal;
return 0;
}
Output
Enter HexaDecimal: 342F
Decimal Number: 13359
Explanation
In the above code, we have created a class HexaToDecimal, one char type array data member hexa[20] to store the hexadecimal, and public member functions getHexa() and HToD() to store and convert the given hexadecimal to decimal number.
In the main() function, we are creating an object H of class HexaToDecimal, reading the hexadecimal given by the user using getHexa() function, and finally calling the HToD() member function to convert the given hexadecimal. The HToD() function contains the logic to convert the given hexadecimal number to a decimal number and printing the result.
C++ Class and Object Programs (Set 2) »