×

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15, with 10 representing A, 11 representing B, 12 representing C, 13 representing D, 14 representing E, and 15 representing F.

Let us look at an example of a program in C++ converting hexadecimal to decimal:

// C++ program to convert hexadecimal to decimal
#include < bits/stdc++.h >
#include < stdlib >
#include < iostream >
using namespace std ; 
// Function to convert hexadecimal to decimal
int hexadecimalToDecimalnum ( string hexVal )
{
	int length = hexValue.size ( ) ; 
	// Initializing base value to 1, i.e 16 ^ 0
	int base = 1 ; 
	int dec_value = 0 ; 
	// extracting characters as digits from last
	// character
	for ( int i = len - 1 ; i >= 0 ; i-- ) {
		// if character lies in ' 0 ' - ' 9 ', converting
		// it to integral 0 - 9 by subtracting 48 from
		// ASCII value
		if ( hexValue [ i ] >= '0' && hexValue [ i ] <= '9' ) {
			dec_value += ( int ( hexValue [ i ] ) - 48 ) * base ;


			// incrementing base by power
			base = base * 16 ;
		}
		// if character lies in 'A' - 'F' , converting
		// it to integral 10 - 15 by subtracting 55
		// from ASCII value
		else if ( hexValue [ i ] >= 'A' && hexValue [ i ] <= 'F' ) {
			dec_value += ( int ( hexValue [ i ] ) - 55 ) * base ;


			// incrementing base by power
			base = base * 16 ;
		}
	}
	return dec_value ;
}
// driver program
int main ( )
{
	string hexNumber = "CAA" ;
	cout << ( hexadecimalToDecimalnum ( hexNumber ) ) ;
	return 0 ;
} 

OUTPUT:

3242
……..
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

The goal is to maintain a dynamic dec_value and subtract the digits of the total hexadecimal number starting from the most right digit. Multiply the digit with the correct base (16 Power) and add it to the variable dec_value when subtracting hexadecimal number digits. Finally, the decimal number will be saved in the variable dec_value.

Another Example:

#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
#include < string >
using namespace std ;
//convert hexadecimal to decimal
int convert ( char num [ ] ) {
   int len = strlen ( num ) ;
   int base = 1 ;
   int temp = 0 ;
   for ( int i = len - 1 ; i >= 0 ; i-- ) {
      if ( num [ i ] >= '0' && num [ i ] <= '9' ) {
         temp += ( num [ i ] - 48 ) * base ;
         base = base * 16 ;
      }
      else if ( num [ i ] >= 'A' && num [ i ] <= 'F' ) {
         temp += ( num [ i ] - 55 ) * base ;
         base = base * 16 ;
      }
   }
   return temp ;
}
int main ( ) {
   char num [ ] = "CAA" ;
   cout << num << " after converting to decimal becomes : " << convert ( num ) <<endl ;
   return 0 ;
}

OUTPUT:

CAA after converting to decimal becomes: 3242
………………………………………………………………………
Process executed in 0.12 seconds
Press any key to continue.

Explanation:

In the above program in C++, we will extract digits from right to left through a remainder, then multiply it with a power starting at 0 and increasing by 1 until the (number of digits) – 1 value is reached. Because we'll be converting from hexdecimal to binary, the power base will be 16, as octal has a base of 16. Multiply the digits of the provided inputs by base and power then save the results. To get the final result, which will be a decimal number, add all the multiplied values together.

Let us look at an example of a program using pre defined function in C++ converting hexadecimal to decimal:

// C++ program to convert octal to decimal
#include < bits/stdc++.h >
#include < iostream >
#include < stdlib >
using namespace std ;
int HexToDecimal ( string n ) { 
return stoi ( n , 0 , 16 ) ; 
}
int main ( )
{
	string n = "CAA" ;
	cout << HexToDecimal ( n ) ; 
	return 0 ;
}

OUTPUT:

3242
……..
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

In the above program in C++, we are using HexToDecimal function which we are passing string n and returning the stoi to get our hexadecimal to decimal number.


Related Topics

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.