Search This Blog

Program to Convert Decimal Number to Hexadecimal Number

This program is to convert a number in decimal number system (base 10) to a hexadecimal number (base 16). I have wrote a function reversestring to reverse a string. You may use strrev function instead if available. The program is as follows:

#include<stdio.h>
#include<string.h>

char* reversestring(char *a)
{
int i,l;
char *r;
l=strlen(a);
r=(char*)malloc(l*sizeof(char));
for(i=0;i<l;i++)
 r[i]=*(a+l-i-1);
r[i]='\0';
return r;
}

char*DecToHex(int dec)
{
char hex[10];
int i=0,tnum,rem;
tnum=dec;
while(tnum!=0)
{
rem=tnum%16;
hex[i++]=rem<=9?'0'+rem:'A'+rem-10;
tnum/=16;
}
hex[i]='\0';
return(reversestring(hex));
}

void main()
{
int inputnum;
printf("\nEnter the decimal number\n");
scanf("%d",&inputnum);
printf("Corresponding hexadecimal is: %s",DecToHex(inputnum));
}

No comments: