Spread the love

Write a c Program to convert decimal to Hexadecimal number

Hexadecimal number system: It is base 16 number system which uses the digits from 0 to 9 and A, B, C, D, E, F. Used by computers to easily represent binary numbers.

Decimal number system: It is base 10 number system which uses the digits from 0 to 9. Used by humans.

 

#include<stdio.h>


int main()
{
    long int decimalNumber=17;
	int remainder;
	int quotient;
    int i=1,j;
    char hexadecimalNumber[100];

    quotient = decimalNumber;

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

      //To convert integer into character
      if( remainder < 10)
           remainder = remainder + 48;		// Add 48(become ascii later) value to remainder if less than 10--see ascii table for more info
      else
         remainder = remainder + 55;		// Add 55(become ascii later) value to remainder if greater than 10--see ascii table for more info

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

    printf("Equivalent hexadecimal value of %d is: ",decimalNumber);


    for(j = i -1 ;j> 0;j--)
      printf("%c",hexadecimalNumber[j]);

    return 0;
}

 

 

Decimal to hexadecimal conversion algorithm:

Following steps describe how to convert decimal to hexadecimal

Step 1: Divide the original decimal number by 16

Step 2: Adjust the remainder by adding 48 or 55  and store in in char array 

Why 48 for less than 10 and 55 for greater than 10 ?

For example: if decimal is 17 then dividing it by 16, gives 1 as a remainder. Now 1 is less than 10, so we add 48 to 1 and it become 49 which is ASCII value of 1 in as you can see in ASCII table below pic.

Same as if we take example of 12 as a decimal number which is ‘C’ in hex. So remainder become 12 and we add it with 55 which becomes 67 which is ASCII  value of ‘C’. See ASCII table below

Step 3: Divide the quotient by 16

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

Decimal to hexadecimal conversion example:

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

17/ 16 gives Remainder : 1 , Quotient : 1
1 / 16 gives  Remainder : 1 , Quotient : 0

So equivalent hexadecimal number is: 11
That is (17)10 = (11)16

ASCII TABLE

Suggested Reading

  1. Convert decimal number into hexadecimal octal binary – single universal logic
  2. Binary representation of a given number