A decimal number uses base 10, while a hexadecimal number uses base 16 with digits 0–9 and A–F, where A–F represent values from 10–15. To convert a decimal number to hexadecimal, we repeatedly divide the number by 16 and use the remainders to form the hexadecimal representation.
- The remainders are stored and printed in reverse order to obtain the final hexadecimal number.
- Each remainder from 10 to 15 is represented using A to F.
Examples:
Input: 2545
Output: 9F1Input: 100
Output: 64

Algorithm for Decimal to Hexadecimal Conversion
The conversion can be performed using repeated division by 16.
1. Initialize a character array to store the hexadecimal digits.
2. While the decimal number is greater than 0:
- Find the remainder by taking n % 16.
- Convert the remainder into its corresponding hexadecimal character.
- Store the character in the array.
- Divide n by 16.
3. The remainders are obtained from right to left, so print the stored characters in reverse order.
For remainders from 0 to 9, use characters 0 to 9. For remainders from 10 to 15, use characters A to F.
#include <iostream>
using namespace std;
// Function to convert decimal to hexadecimal
void decToHexa(int n)
{
// Array to store hexadecimal digits
char hexaDeciNum[100];
// Index for storing digits
int i = 0;
while (n != 0)
{
// Get the remainder after division by 16
int remainder = n % 16;
// Convert remainder to hexadecimal character
if (remainder < 10)
hexaDeciNum[i] = '0' + remainder;
else
hexaDeciNum[i] = 'A' + (remainder - 10);
i++;
// Reduce the number for the next iteration
n /= 16;
}
// Remainders are stored in reverse order,
// so print them from right to left
for (int j = i - 1; j >= 0; j--)
cout << hexaDeciNum[j];
}
int main()
{
int n = 2545;
decToHexa(n);
return 0;
}
Output
9F1
Explanation: For n = 2545, the program repeatedly divides the number by 16 and stores the remainders.
- 2545 ÷ 16 = 159, remainder 1 -> 1
- 159 ÷ 16 = 9, remainder 15 -> F
- 9 ÷ 16 = 0, remainder 9 -> 9
- The remainders are obtained as 1, F, 9, so they are printed in reverse order.
- Therefore, the hexadecimal equivalent of 2545 is 9F1.
2545₁₀ = 9F1₁₆