Pages

CTechnotips: Decimal to hexadecimal conversion in c language

Hexadecimal number system: It is base 16 number system which uses the digits from 0 to 9 and A, B, C, D, E, F.

Decimal number system:

It is base 10 number system which uses the digits from 0 to 9

Following steps describe how to convert decimal to hexadecimal

Step 1: Divide the original decimal number by 16

Step 2: Divide the quotient by 16

Step 3: Repeat the step 2 until we get quotient equal to zero.

Equivalent binary number would be remainders of each step in the reverse order.

For example we want to convert decimal number 900 in the hexadecimal.

Step 1:  900 / 16  Remainder : 4 , Quotient : 56

Step 2:   56 / 16  Remainder : 8 , Quotient : 3

Step 3:    3 / 16  Remainder : 3 , Quotient : 0

So equivalent hexadecimal number is: 384

That is (900)10 = (384)16

1. C code to convert decimal to hexadecimal

#include<stdio.h>
int main(){
long int decimalNumber,remainder,quotient;
int i=1,j,temp;

printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);

quotient = decimalNumber;

while(quotient!=0){
temp = quotient % 16;

//To convert integer into character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;

quotient = quotient / 16;
}

printf("Equivalent hexadecimal value of decimal number %d: ",decimalNumber);
for(j = i -1 ;j> 0;j--)

return 0;
}

Sample output:

Enter any decimal number: 45
Equivalent hexadecimal value of decimal number 45: 2D

2. Easy way to convert decimal number to hexadecimal number:

#include<stdio.h>
int main(){

long int decimalNumber;

printf("Enter any decimal number: ");
scanf("%d",&decimalNumber);

return 0;
}

Sample output:

Enter any decimal number: 45