C++ Code Example: convert decimal to hexadecimal number

This program converts a decimal number to a hexadecimal number.

Code Example

#include <iostream>
using namespace std;

int main() {
    int num, remainder, decimal, product = 1;
    char c;
    string hex = "";

    cout << "Please enter a number: ";
    cin >> num;

    decimal = num;

    while (decimal != 0) {
        remainder = decimal % 16;
        if (remainder >= 10) {
            c = remainder + 55;
        } else {
            c = remainder + 48;
        }
            
        hex += c;
        decimal = decimal / 16;
        product *= 10;
    }

    reverse(hex.begin(), hex.end());

    cout << "Hexadecimal value of number: " << num << " is: " << hex << endl;
}
Output
Please enter a number: 1234
Hexadecimal value of number: 1234 is: 4D2

Code Explanation

    1. The #include <iostream> header file is included, which allows us to use the cin and cout streams for input and output.
    2. The main() function is declared and executed when the program runs.
    3. A variable num is declared and initialized to store the decimal number entered by the user.
    4. A variable remainder is declared to store the remainder obtained from dividing the decimal number by 16.
    5. A variable decimal is declared and initialized to the value of num.
    6. A while loop is used to continue converting the decimal number to hexadecimal until the decimal number is equal to 0.
    7. Within the while loop, the remainder is obtained by dividing the decimal by 16.
    8. An if statement checks if the remainder is greater than or equal to 10. If it is, then it converts the remainder to its corresponding hexadecimal character. This is done by adding 55 to the remainder as the ASCII value of A (the first letter in hexadecimal) is 65.
    9. If the remainder is less than 10, then it is converted to its corresponding hexadecimal character by adding 48 to the remainder. The ASCII value of 0 is 48.
    10. The resulting hexadecimal character is appended to the hex string.
    11. The decimal number is updated by dividing it by 16.
    12. The loop continues until the decimal is equal to 0.
    13. Once the loop is finished, the hex string is reversed using the reverse() function from the algorithm library.
    14. The final hexadecimal number is output to the console using cout.
    15. The main() function returns 0 to indicate that the program has run successfully.