How to convert a number from decimal to hexadecimal in C++

In this shot, we will discuss how to convert a decimal number to a hexadecimal number in C++.

When we convert a decimal number to a hexadecimal number, we divide the number by 1616. Then, we divide the quotient by 1616 again. We repeat the process until the quotient becomes 00.

We will take the hexadecimal in type string. Hexadecimal number values range between 00 to 99 and then AA to FF.

Let’s look at the hexadecimal values and their equivalent decimal counterparts.

Decimal and Hexadecimal Values

Code

Take a look at the code snippet below to understand this better.

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int decimal, remainder, product = 1;
string hex_dec = "";
cin >> decimal;
while (decimal != 0) {
remainder = decimal % 16;
char ch;
if (remainder >= 10)
ch = remainder + 55;
else
ch = remainder + 48;
hex_dec += ch;
decimal = decimal / 16;
product *= 10;
}
reverse(hex_dec.begin(), hex_dec.end());
cout << "The number in the hexadecimal form is: " <<hex_dec;
}

Enter the input below

Enter a number in the input section above.

Explanation

  • In line 6, we initialize the variables decimal, remainder, and product.

  • In line 7, we initialize the variable hex_dec as a string. This string will store the result in reverse order.

  • In line 9, we take decimal as input.

  • From lines 10 to 20, we initialize a while loop. In the loop, we calculate the remainders and quotients as discussed in the above illustration to convert the decimal number to its hexadecimal equivalent. In line 12, we initialize a variable ch of char type that stores each of the hexadecimal values for the decimal digits.

  • In line 22, we use the reverse() function to print the output in hexadecimal form.

  • In line 23, we print the output, i.e., the hexadecimal equivalent of the decimal number.

This way, we can convert the value of a decimal number to a hexadecimal number.

Free Resources