×

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

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

C++ Continue in Do-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 start...

4 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.