C program to convert decimal to hexadecimal

Updated on 06th January 2016

A decimal number as we all know uses 10 symbols from 0 to 9 to represent any number. Hexadecimal number system, also called hex, uses the 10 symbols 0 to 9 from the decimal number system and an additional 6 English alphabets from A to F. A hexadecimal A is equivalent to a decimal 10, Hex B equals Decimal 11, Hex F equal Decimal 15 and Hex 10 equal Decimal 16. This is a C program to convert a decimal number to its hexadecimal equivalent.

The method used for this conversion is to repeatedly divide the decimal number by 16 and store the remainder in an array. Finally when the array is printed out, the program checks if the array element is less than 10 in which case then it is printed as decimal number using %d format modifier. If array element is greater than or equal to 10 then its corresponding English alphabet is obtained by adding 55 and the value printed out as character using %c format modifier.

Program Source Code

/* **********************************************
 * C program to convert Decimal to Hexadecimal	*


int main() 
 int num, hex_num[20], dec_num, i, j;

 // Read a Decimal number
 printf("Enter a decimal number : ");
 dec_num = num;

 // Convert Decimal to Hexadecimal
 while (dec_num) {
	hex_num[i] = dec_num % 16;
	dec_num = dec_num / 16;
 // Print the hexadecimal value
 printf("Hexadecimal Value of %d is ",num);
 for (j=i-1; j>=0; j-- ) {
	 if (hex_num[j] < 10)
		  // print 0-9
	 	 // print A-F
		printf("%c",hex_num[j] + 55);

 //Wait for key press
 printf("\n\nPress any key to continue...");

 return 0;

Sample Output

Enter a decimal number : 50
Hexadecimal Value of 50 is 32

Press any key to continue...

Post a comment

Got a question about this article? Ask our forum


Your Comment

Email (We dont publish it)


Nothing yet..be the first to share wisdom.