×

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

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 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.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 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.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

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.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.