C++ program to convert decimal to hexadecimal
Written by
Convert Decimal to Hexadecimal program in C++
A decimal number is taken as input and converted it into its hexadecimal equivalent.
Example:
Decimal number: 77
Corresponding hexadecimal number: 4D
Decimal number: 50
Corresponding hexadecimal number: 32
Algorithm:
- Prompt the user to input a decimal number.
- Store the number in a variable
dno
. - Initialize a variable
temp
todno
. - Initialize an empty list
hex
to store the hexadecimal equivalent of the decimal number. - Use a
while
loop to repeatedly dividetemp
by 16 and store the remainder in a variableremainder
. - Convert the remainder to its hexadecimal equivalent by adding the appropriate ASCII value (either 48 for digits 0-9 or 55 for letters A-F).
- Append the hexadecimal equivalent of the remainder to the
hex
list. - Divide
temp
by 16 and store the result back intemp
. - Repeat this process until
temp
is 0. - Print the hexadecimal equivalent of the decimal number by iterating through the
hex
list in reverse order. - Exit the program.
Code:
#include <iostream>
using namespace std;
int main() {
long int dno, temp;
char hex[100];
int j, remainder, i = 1;
cout << "Enter Decimal Number: ";
cin >> dno;
temp = dno;
while (temp != 0) {
remainder = temp % 16;
if (remainder < 10) { // Converts integer into character
remainder = remainder + 48;
} else {
remainder = remainder + 55;
}
hex[i++] = remainder;
temp = temp / 16;
}
cout << "\nHexadecimal Number corresponding to Decimal Number: ";
for (j = i - 1; j > 0; j--) {
cout << hex[j];
}
return 0;
}
Output
Enter Decimal Number: 255
Hexadecimal Number corresponding to Decimal Number: FF