# Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a base value of 10 to a number with a base value of 16.

A number in hexadecimal format is represented by 16 values. Numbers 0-9 are represented by digits 0-9, and numbers 10 to 15 are represented by letters A to F.

Let see an example of a program in C++ to convert decimal to hexadecimal number:

``````// C++ program to convert a decimal
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ;
// function to convert decimal to hexadecimal
void decToHexadecimal ( int n )
{
// char array to store hexadecimal number
char hexaDeciNumber [ 100 ] ;
// counter for hexadecimal number array
int i = 0 ;
while ( n != 0 ) {
// temporary variable to store remainder
int temp = 0 ;
// storing remainder in temp variable.
temp = n % 16 ;
// check if temp < 10
if ( temp < 10 ) {
hexaDeciNumumber [ i ] = temp + 48 ;
i++ ;
}
else {
hexaDeciNumber [ i ] = temp + 55 ;
i++ ;
}
n = n / 16 ;
}
// printing hexadecimal number array in reverse order
for ( int j = i - 1 ; j >= 0 ; j-- )
cout << hexaDeciNumber [ j ] ;
}
// Driver program to test above function
int main ( )
{
int n = 3242 ;
return 0 ;
}
``````

OUTPUT:

``````CAA
……
Process executed in 0.11 seconds
Press any key to continue
``````

Explanation:

When an integer is divided by 16, the residue is stored in a temporary variable called temp. If the temperature is less than 10, put (48 + temp) in a character array; otherwise, put (55 + temp) in the character array if the temperature is more than or equal to 10. Now multiply the number by 16 to get the answer. Repeat steps 1 and 2 until the number is not equal to 0. Now reverse the order of the array.

Let us look at an example using pre defined function in C++:

``````// C++ program to convert decimal number to hexadecimal
#include <iostream>
using namespace std;
// function to convert decimal number to hexadecimal
void decToHexa(int n) { cout << hex << n << endl; }
// driver code
int main()
{
int n = 3242;
decToHexa(n);
return 0;
}
// C++ program to convert decimal number to hexadecimal
#include <iostream>
using namespace std;
// function to convert decimal number to hexadecimal
void decToHexa(int n) { cout << hex << n << endl; }
// driver code
int main()
{
int n = 3242;
decToHexa(n);
return 0;
}
``````

OUTPUT:

`CAA`

Explanation:

In the above program we are using decTohexa function which makes the call with parameter n which is our decimal number.