Decimal Number System:
It is base 10 number system which uses the digits from 0 to 9.
Hexadecimal Number System:
It is base 16 number system which uses the digits from 0 to 9 and A, B, C, D, E, F.
Logic to Convert Decimal to Hexadecimal C++:
- Divide the original decimal number by 16.
- Divide the quotient by 16.
- Repeat the step 2 until we get quotient equal to zero.
- Equivalent Hexadecimal number would be the remainders of each step in the reverse order.
Download Source Code:
[adinserter block=”1″]
Download: dectohex.cpp
PROGRAM:
#include<iostream>
using namespace std;
int main()
{
long int decimalNumber,remainder,quotient;
int i=1,j,temp;
char hexadecimalNumber[100];
cout<<"Enter any decimal number: ";
cin>>decimalNumber;
quotient = decimalNumber;
while(quotient!=0)
{
temp = quotient % 16;
//To convert integer into character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexadecimalNumber[i++]= temp;
quotient = quotient / 16;
}
cout<<"nEquivalent hexadecimal number of "<<decimalNumber<<" is : ";
for(j = i -1 ;j> 0;j--)
cout<<hexadecimalNumber[j];
cout<<endl;
return 0;
}
How Code Works:
Let user enter 900.
- 900 / 16 Remainder : 4 , Quotient : 56
- 56 / 16 Remainder : 8 , Quotient : 3
- 3 / 16 Remainder : 3 , Quotient : 0
Now Hexadecimal Number is remainders in each step in reverse order i.e. 384
Hence, hexadecimal equivalent of 900 is 384.