C++ program to convert decimal to hexadecimal

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:

  1. Prompt the user to input a decimal number.
  2. Store the number in a variable dno.
  3. Initialize a variable temp to dno.
  4. Initialize an empty list hex to store the hexadecimal equivalent of the decimal number.
  5. Use a while loop to repeatedly divide temp by 16 and store the remainder in a variable remainder.
  6. 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).
  7. Append the hexadecimal equivalent of the remainder to the hex list.
  8. Divide temp by 16 and store the result back in temp.
  9. Repeat this process until temp is 0.
  10. Print the hexadecimal equivalent of the decimal number by iterating through the hex list in reverse order.
  11. 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

C++ program to convert decimal to hexadecimal