C++ Program to Convert Decimal to Hexadecimal
std::stringstream with std::hex manipulator like this: std::stringstream ss; ss << std::hex << decimalNumber; std::string hexStr = ss.str();.Examples
How to Think About It
Algorithm
Code
#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; }
Dry Run
Let's trace the decimal number 26 through the code to convert it to hexadecimal.
Input
decimalNumber = 26
Check if zero
26 is not zero, continue
First division
26 % 16 = 10 (remainder), 26 / 16 = 1 (quotient) hexNumber = 'a' (hexDigits[10])
Second division
1 % 16 = 1 (remainder), 1 / 16 = 0 (quotient) hexNumber = 'a' + '1' = 'a1'
Reverse string
hexNumber reversed from 'a1' to '1a'
Output
Print 'Hexadecimal: 1a'
| decimalNumber | remainder | hexNumber (before reverse) |
|---|---|---|
| 26 | 10 (a) | a |
| 1 | 1 | a1 |
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
#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; }
#include <cstdio> int main() { int decimalNumber; printf("Enter a decimal number: "); scanf("%d", &decimalNumber); printf("Hexadecimal: %x\n", decimalNumber); return 0; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual division and remainder | O(log n) | O(log n) | Learning and understanding conversion |
| std::stringstream with std::hex | O(log n) | O(log n) | Simple and modern C++ code |
| printf with %x | O(log n) | O(1) | Quick and concise C-style output |