Decimal to Hexadecimal
C |
Intermediate |
25 Aug 2006 |
*** |
This page will list the program for converting a Decimal number to its corresponding Hexadecimal form.
/*Program to convert Decimal to Hex
Author: Midhun Harikumar
Support:
*/
# include <conio.h>
# include <stdio.h>
char itohex(int);
int main()
{
char hex[80],dex[10];
int i=0,deci,tmp,d1,j;
float input,mantissa,f1,f2;
printf("Decimal to Hex Converter\n\n");
printf("Enter a decimal Number ... ");
scanf("%f",&input);
deci = (int) input;
mantissa = input - deci;
while(deci>0)
{
tmp = deci % 16;
deci /= 16;
hex[i] = itohex(tmp);
i++;
}
// Mantissa Part
f1 = mantissa;
for(j=0;j<5;j++) //for 5 digits after decimal point
{
f2 = 16 * f1;
d1 = (int)f2;
dex[j] = itohex(d1);
f1 = f2 - d1; }
// Display
printf("The corresponding Hexadecimal value is ... ");
for(--i;i>=0;i--)
printf("%c",hex[i]);
printf(".");
for(j=0;j<5;j++) printf("%c",dex[j]);
return 0;
}
//Function that returns character corresponding to a number
char itohex(int num)
{
switch(num)
{case 0 : return '0';break;
case 1 : return '1';break;
case 2 : return '2';break;
case 3 : return '3';break;
case 4 : return '4';break;
case 5 : return '5';break;
case 6 : return '6';break;
case 7 : return '7';break;
case 8 : return '8';break;
case 9 : return '9';break;
case 10: return 'A';break;
case 11: return 'B';break;
case 12: return 'C';break;
case 13: return 'D';break;
case 14: return 'E';break;
case 15: return 'F';break;
default: return '0';
}
} |
Description
A decimal integer is converted to hex by applying repeated division using 16. The modulus values are used to get the hex value. For converting a decimal fraction, ie: to the right of the decimal point, we use repeated multiplication until the required precision is met. The whole number part of these fractions is used for getting the hex for the part after the decimal point.
There are a number of ways in which this program can be implemented. What we have done here is convert the part to the left of the decimal part first to a character array, then convert the decimal part after the decimal point to hex to another array. Since we must use a string to store the hex, we use the function itohex() for getting the hexadecimal equivalent of an integer.
When a float is equated to an integer, the decimal part to the right of the decimal point is lost. This is how we get the integer part from a float. To get the part after the decimal point, subtract the integer part from the original float number.