0
0
CppProgramBeginner · 2 min read

C++ Program to Convert Decimal to Hexadecimal

You can convert a decimal number to hexadecimal in C++ by repeatedly dividing the number by 16 and storing remainders, or simply using std::stringstream with std::hex manipulator like this: std::stringstream ss; ss << std::hex << decimalNumber; std::string hexStr = ss.str();.
📋

Examples

Input26
Output1a
Input255
Outputff
Input0
Output0
🧠

How to Think About It

To convert decimal to hexadecimal, think of dividing the decimal number by 16 repeatedly. Each division gives a remainder between 0 and 15, which corresponds to a hex digit (0-9 or a-f). Collect these remainders in reverse order to form the hexadecimal number.
📐

Algorithm

1
Get the decimal number as input.
2
If the number is zero, return '0' as the hexadecimal.
3
While the number is greater than zero, divide it by 16 and record the remainder.
4
Convert each remainder to its hexadecimal character (0-9, a-f).
5
Append each character to a string or stack.
6
Reverse the collected characters to get the final hexadecimal string.
💻

Code

cpp
#include <iostream>
#include <string>
#include <algorithm>

int main() {
    int decimalNumber;
    std::cout << "Enter a decimal number: ";
    std::cin >> decimalNumber;

    if (decimalNumber == 0) {
        std::cout << "Hexadecimal: 0" << std::endl;
        return 0;
    }

    std::string hexNumber = "";
    const char hexDigits[] = "0123456789abcdef";

    while (decimalNumber > 0) {
        int remainder = decimalNumber % 16;
        hexNumber += hexDigits[remainder];
        decimalNumber /= 16;
    }

    std::reverse(hexNumber.begin(), hexNumber.end());
    std::cout << "Hexadecimal: " << hexNumber << std::endl;
    return 0;
}
Output
Enter a decimal number: 26 Hexadecimal: 1a
🔍

Dry Run

Let's trace the decimal number 26 through the code to convert it to hexadecimal.

1

Input

decimalNumber = 26

2

Check if zero

26 is not zero, continue

3

First division

26 % 16 = 10 (remainder), 26 / 16 = 1 (quotient) hexNumber = 'a' (hexDigits[10])

4

Second division

1 % 16 = 1 (remainder), 1 / 16 = 0 (quotient) hexNumber = 'a' + '1' = 'a1'

5

Reverse string

hexNumber reversed from 'a1' to '1a'

6

Output

Print 'Hexadecimal: 1a'

decimalNumberremainderhexNumber (before reverse)
2610 (a)a
11a1
💡

Why This Works

Step 1: Divide by 16 to find remainder

Each remainder from dividing by 16 represents one hex digit because hexadecimal is base 16.

Step 2: Map remainder to hex digit

Remainders 0-9 map to '0'-'9', and 10-15 map to 'a'-'f' to represent hex digits.

Step 3: Reverse collected digits

Digits are collected from least significant to most significant, so reversing them gives the correct hex number.

🔄

Alternative Approaches

Using std::stringstream and std::hex
cpp
#include <iostream>
#include <sstream>

int main() {
    int decimalNumber;
    std::cout << "Enter a decimal number: ";
    std::cin >> decimalNumber;

    std::stringstream ss;
    ss << std::hex << decimalNumber;
    std::string hexStr = ss.str();

    std::cout << "Hexadecimal: " << hexStr << std::endl;
    return 0;
}
This method is simpler and uses built-in C++ features but may be less educational about the conversion process.
Using printf with %x format specifier
cpp
#include <cstdio>

int main() {
    int decimalNumber;
    printf("Enter a decimal number: ");
    scanf("%d", &decimalNumber);
    printf("Hexadecimal: %x\n", decimalNumber);
    return 0;
}
This is the shortest method using C-style IO, but mixing C and C++ styles is less modern.

Complexity: O(log n) time, O(log n) space

Time Complexity

The loop runs once for each hex digit, which is proportional to the logarithm base 16 of the decimal number.

Space Complexity

Extra space is used to store the hex digits, proportional to the number of digits (log base 16 of the number).

Which Approach is Fastest?

Using printf or stringstream is faster and simpler for practical use, but manual division teaches the conversion logic.

ApproachTimeSpaceBest For
Manual division and remainderO(log n)O(log n)Learning and understanding conversion
std::stringstream with std::hexO(log n)O(log n)Simple and modern C++ code
printf with %xO(log n)O(1)Quick and concise C-style output
💡
Remember to reverse the collected hex digits because you get them from least to most significant digit.
⚠️
Beginners often forget to reverse the string of hex digits, resulting in the wrong output.