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 . Then, we divide the quotient by again. We repeat the process until the quotient becomes .
We will take the hexadecimal in type string. Hexadecimal number values range between to and then to .
Let’s look at the hexadecimal values and their equivalent decimal counterparts.
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;elsech = 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, andproduct. -
In line 7, we initialize the variable
hex_decas a string. This string will store the result in reverse order. -
In line 9, we take
decimalas 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
chofchartype 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.