Decimal to Hexadecimal Conversion
“Decimal to Hexadecimal Conversion” is a one of the classic programming problem exercise for beginners. Here, we are given a Decimal Number, entered by user and our task is to write a program to convert the given Decimal Number to its equivalent Hexadecimal Number.
Hexadecimal Numbers uses 16 values to represent the number. Numbers from 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A – F.
Examples (Decimal to Hexadecimal Conversion):
Decimal = 15 Hexadecimal = A Decimal = 78 Hexadecimal = 4E
The steps required for decimal to hexadecimal conversion are as follows:
- Initialize an empty string which will store hexadecimal number.
- Store the remainder when the decimal number is divisible by 16.
- If the remainder is less than 10, then convert the remainder number into character by (remainder + 48) and insert it to hexadecimal string at the front.
- Else if the remainder is greater than 9, then convert the remainder number into character by (remainder + 55) and insert it to hexadecimal string at the front.
- Divide the decimal number by 16.
- Repeat the steps from 2 to 5 until decimal number is greater than 0.
- Print the Hexadecimal number.
C++ Program for Decimal to Hexadecimal Conversion is as follows:
/* C++ Program for Decimal to Hexadecimal Conversion */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan the Decimal Number */
int Decimal;
cout<<"Enter the Decimal Number: ";
cin>>Decimal;
/* Converting Decimal to Hexadecimal */
string Hexadecimal;
int temp = Decimal;
while(temp!=0)
{
int remainder = temp % 16;
if(remainder >=0 && remainder <=9)
{
char ch = remainder + 48;
Hexadecimal = ch + Hexadecimal;
}
else
{
char ch = remainder + 55;
Hexadecimal = ch + Hexadecimal;
}
temp = temp / 16;
}
/*Printing the result */
cout<<"The Hexadecimal of "<<Decimal<<" is "<<Hexadecimal;
}
OUTPUT: Enter the Decimal Number: 78 The Hexadecimal of 78 is 4E
Related Posts:
- Program to convert decimal number to binary number.
- Program to convert decimal number to octal number.
- Program to convert hexadecimal number to binary number.
- Program to convert hexadecimal number to octal number.
- Program to convert hexadecimal number to decimal number.
- Program to convert binary number to octal number.
- Program to convert binary number to decimal number.
- Program to convert binary number to hexadecimal number.
- Program to convert octal number to binary number.
- Program to convert octal number to decimal number.
- Program to convert octal number to hexadecimal number.
- Program to print Fibonacci Series up to Nth Term.
- Program to find and print nth Fibonacci number.
- Program to find Power of the Number.
- Program to find Quotient and Remainder.
- Program to find largest amongst three numbers.
- Program to find factorial of a number.
- Program to find GCD of two numbers.
- Program to find LCM of two numbers.
- Program to check whether entered number is odd or even.