Decimal to hexadecimal conversion in c





1. C code to convert decimal to hexadecimal

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

    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;

      hexadecimalNumber[i++]= temp;
      quotient = quotient / 16;
  }

    printf("Equivalent hexadecimal value of decimal number %d: ",decimalNumber);
    for(j = i -1 ;j> 0;j--)
      printf("%c",hexadecimalNumber[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);

  printf("Equivalent hexadecimal number is: %X",decimalNumber);

  return 0;
}

Sample output:

Enter any decimal number: 45
Equivalent hexadecimal number is: 2D

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

Decimal to hexadecimal conversion method:

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.

Decimal to hexadecimal conversion example:

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






6. Write a c program to convert octal number to hexadecimal number.
8. Write a c program to convert hexadecimal number to octal number.
9. Write a c program to convert hexadecimal number to decimal number.
10. Write a c program to convert binary number to octal number.

Post a Comment