How To Convert Hexadecimal To Decimal In C

Hexadecimal number is a special type of number system which represents data in alphanumeric code. We need first understand what a hexadecimal number is and what a decimal number is. A decimal number has a base of 10. The number of digits required to express a numeric value depends on the base value of the underlying number system.

For example, the decimal number system employs 10 digits 0 to 9 to represent any numeric value. The base-16 numbering scheme is referred to as hexadecimal. The hexadecimal number system is defined as a 16-digit representation of numbers ranging from 0 to 9 and digits A to F.

In other words, the first nine numbers or digits are represented as numbers, whereas the remaining six digits are expressed by the letters A through F. Hexadecimal is quite close to the decimal number system, which has a base of 9. Consequently, after 9 numbers, the 10th digit is represented by a symbol: 10, 11, 12, 13, 14, and 15, respectively. So, the 16 numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F.

Here, we'll see how to build a C program that will translate a given hexadecimal number into its equivalent decimal number.   

Example: Example: Following numbers are decimal numbers having base 10

32, 128, 150, 845, 525, 52652

Example: Following numbers are represented in the hexadecimal numbers.

5E, C9, 1FD, 8FA2, A485B

Hexadecimal numerals include place values similar to how decimal numbers do, such as ones, tens, hundreds, thousands, etc. Hexadecimal powers are 16, while decimal powers are 10. The following table demonstrates how the hexadecimal & decimal numbering system handles place values:

Decimal Number System

Exponent105104103102101100
Values100000100001000100101

Hexadecimal Number System

xponent165164163162161160
Values1048576655364096256161

Using the base number 16, hexadecimal to decimal conversion is performed. Each digit in the enlarged hexadecimal number is multiplied by 16 for each digit. As power increases, the power increases from the right starting at 0 and moves ahead towards the right. The multiplied numbers must be added for the conversion to be complete. To convert hexadecimal to decimal, follow these steps:

  •  Starting at 0 from the right, multiply each digit by a factor of 16 one more times.
  •  Add all the numbers together.

General Algorithm:  The following Algorithm is used to convert hexadecimal to decimal values:

Step 1: The base of the number that needs to be transformed is 16.

Step 2: Beginning with the rightmost digit, multiply each digit of the given integer by the exponents of the base 16.

Step 3: As we proceed from right to left, the exponents should begin at 0 and rise by 1 each time.

Step 4: Add each of the products after simplifying it.

Formula : Decimal Number = dm-1 × 16q-1+….+ d2 × 162 + d1 × 161 + d0 × 160

Where:

Ø  m = number of digits.

Ø  q = placement of the digit.

Ø  di = Digit at ith place of given number

To further grasp this, let’s look at an illustration. For example: Convert hexadecimal number (1FD)16 to its equivalent decimal number.

Step 1: (1FD)16 = 1 * 162 + F * 161 + D* 160

Step 2: (1FD)16 = 1 * 162 + 15 * 161 + 13* 160

Step 3: (1FD)16 = 1 * 256 + 15 * 16 + 13* 1

Step 4: (1FD)16 = 1 * 256 + 15 * 16 + 13* 1

Step 5: (1FD)16 = (509)10

Why Is There A Need To Convert Hexadecimal to Decimal In C

Programmers frequently employ the hexadecimal numbering scheme in place of the binary one to make things simpler. There is a linear relationship between the numbers 2 and 16 because 16 and 24 are equivalent. This indicates that four binary digits are equivalent to one hexadecimal digit.

Humans use hexadecimal number systems to condense binary and make it simpler for people to understand, while computers utilize binary numbering systems. The following uses hexadecimal: We are required to convert the hexadecimal code to the decimal number for the following reasons.   

  • Less Memory Need: Hexadecimal numbers are small and take up less memory, allowing computers to store more of them. Comparatively to other number systems, their little size also makes input-output handling simpler. The method is frequently used in computer programming since it is simple to convert from hexadecimal to binary and vice versa. The fundamental benefit of utilizing hexadecimal numbers is that they use less memory to hold more numbers; for instance, they can store 256 values in two digits, as opposed to 100 for decimal numbers. Computer memory addresses are also represented by this numeric scheme.
  • Color Code Encoding: To specify the colors used on web pages: Two hexadecimal numbers represent each of the three main colors—red, green, and blue. It uses the #RRGGBB format. Red, green, and blue are represented respectively by the letters RR, GG, and BB.
  • MAC (Media Access Control) Addresses Representation: Twelve-digit hexadecimal numbers make up MAC addresses. Either MMMM-MMSS-SSSS or MM:MM:MM:SS:SS:SS is the format that is being used. The MAC address’s last 6 digits correspond to the serial number, while the MAC address’s first 6 digits identify the manufacturer of the device.
  • Error Message Code Representation: The error location in memory is specified using hexadecimal values. In order to identify and correct mistakes, programmers might use this.
  • Security Code Interpretation: In computer security, digital signature is computed in hexadecimal code. Therefore to process that code we convert hex code to decimal numbers.      

Approaches to Convert Hexadecimal to Decimal

Numerous approaches may be used to convert hexadecimal code to decimal numbers. There are some approaches listed and discussed below. 

  • Approach-1: Using While Loop
  • Approach-2: Using %x and %d  Format Specifier
  • Approach-3: Using For Loop with Switch Case Statement

Lets dive in details for each approach.

Approach-1: Using While Loop

In order to convert a hexadecimal number to a decimal number in C programming, we must first ask the user to enter the hexadecimal number to be converted, and then print its decimal equivalent.. An algorithm for this approach is represented in the following steps.

Algorithm:

Step-1: Taking hexadecimal code as an input string from the user and store into a variable.

Step-2: Check the ascii value of each character of the input string.

Step-3: Decimal number is computed according to ascii value and numbers..

To demonstrates this approach, a program is created which code is given below:

Code:

// C program to demonstrates conversion of hexadecimal to decimal
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
	int dn=0, r, k=0, l=0;
	char hdn[25];
	printf("Enter any Hexadecimal Number for conversion into decimal number: ");
	scanf("%s", hdn);
	while(hdn[k]!='\0')
	{
    	l++;
    	k++;
	}
	l--;
	k=0;
	while(l>=0)
	{
    	r = hdn[l];
    	if(r>=48 && r<=57)
        	r = r-48;
    	else if(r>=65 && r<=70)
        	r = r-55;
    	else if(r>=97 && r<=102)
        	r = r-87;
    	else
    	{
        	printf("\n The given number is not Hexadecimal number");
        	getch();
        	return 0;
    	}
    	dn = dn + (r*pow(16, k));
    	l--;
    	k++;
	}
	printf("\n The Equivalent Decimal Value: %d", dn);
	getch();
	return 0;
}

Output:

Enter any Hexadecimal Number for conversion into decimal number: 1fd
The Equivalent Decimal Value: 509

Code Explanation:

  1. Take as input any hexadecimal number.
  2. A character array is used to hold the inputted hexadecimal number.
  3. To determine the size of the character array, use a while loop.
  4. Using either l– or l=l-1, reduce the length value by one after determining the length of the given hexadecimal integer.
  5. Since an array’s indexing begins at 0. Because we’re going to utilize k as a 16th exponent, initialize k to 0.
  6. The ASCII codes for 0-9 are 48-57 and for A-F (which are represented by the hexadecimal values 10-15) are 65-70. We therefore used a specific hexadecimal digit’s ASCII code to check and initialize the associated decimal value of that hexadecimal digit.
  7. r-48, 57-48, or 9 gets initialized to r if hdn[2] contains 9 and the ASCII value for 9 is 56.
  8. Following that, decimal is allocated to dn+ (r*pow(16, k)), 0 + (9*pow(16, 0)), 0 + 9*1, or 9. When l>=0 or 1>=0 evaluates to true, program flow returns to the while loop condition and once more enters the loop.
  9. Executing a related procedure. In other words, r is set for hdn[l], hdn[1] or A. The initialization of r-55, 65-55, or 10 (which represents A in the hexadecimal number system) to r occurs because the ASCII code for the letter A is 65.
  10. Then, dn is set to dn + (r*pow(16, k)) or 9 + (10*161) or 9+160 or 169.
  11. The value of k is increased, whereas the value of l is decreased.
  12. The identical procedure as described in the preceding steps is performed when program flow returns to the condition of the loop.
  13. Following the while loop’s termination, the dn variable, which has the specified hexadecimal number’s equivalent decimal value, is available.
  14. Print the value of the dn variable as output as a result.

Approach-2: Using %x and %d Format Specifier

In C, various format specifiers exist. With the help of %x and %d format specifiers, we can convert hexadecimal numbers to decimal numbers. An algorithm for this approach is represented in the following steps.

Algorithm: 

Step-1: Take a hexadecimal number from the user using %x format specifier in scanf() function.

Step-2: Decimal number is displayed using %d format specifier in printf() function .

Code:

// C program to demonstrates conversion of hexadecimal to decimal using format specifiers
#include <stdio.h>
int main()
{
        	int m; // Enter value of  m as hexadecimal number input from end user
Printf(“Enter hexadecimal number”);
        	scanf("%x", &m); 
        	printf(“Decimal number is: %d", m);// print equivalent decimal number as output
      	return 0;
}

Output:

Enter hexadecimal number: 1fd
Decimal number is: 509

Code Explanation:

  •  
  •  Include header file i.e. stdio.h.
  •  Taking hexadecimal numbers as input from the user using %x.
  • Printing the decimal number equivalent to the  given hexadecimal number as output using %d format specifier.

Approach-3: Using For Loop with Switch Case Statement

With the help of a For loop and switch case statement of C language, we can also convert hexadecimal numbers to decimal numbers. This approach is defined in the following algorithm.

Algorithm: 

Step-1: Takes a hexadecimal code from the user.

Step-2: Calculating length of given hexadecimal number and implementing a For loop for each character / digits of given number in reverse order.

Step-3: Now, from right to left read each character of a given hexadecimal number and use the switch case statement for finding the value as per the input string.

Step-4: If it is a character from A to F, we find the case and if it is a digit we use the default option of switch case statement.

Step-5: After getting the value of the character, implement the formula &amp; increment the power of base (16 for hexadecimal) and then iterate the for loop for all the symbols of the given string.

Step-6: After exhausting the whole string using a for loop we get the equivalent decimal number as output and it is printed.

Code:

// C program to demonstrates conversion of hexadecimal to decimal using for loop and switch case statement
#include <math.h>
#include <stdio.h>
#include <string.h>
int main()
{
char hdn[20];
int dn =0, k, p=0, v;
printf(“Enter the hexadecimal number (use capital letters)”);
scanf(“%s”, hdn);
for (k = (strlen(hdn) - 1); k >= 0; k--) {
switch (hdn[k]) {
case A:
v = 10;
break;
case B:
v = 11;
break;

case C:
v = 12;
break;
case D:
v = 13;
break;
case E:
v = 14;
break;
case F:
v = 15;
break;
default:
v = hdn[k] - 0x30;
}
dn = dn + (v)*pow((double)16, (double)p);
p++;
}
printf(“Decimal number is: %d“, dn); // print an equivalent decimal number
return 0;
}

Output:

Enter the hexadecimal number (use capital letters): 1fd
Decimal number is: 509

Code Explanation:

  1. Taking a hexadecimal number from users in capital letters.
  2. Calculating length of given hexadecimal number and implementing a For loop for each character / digits of given number in reverse order.
  3. Now, from right to left read each character of a given hexadecimal number and use the switch case statement for finding the value as per the input string.
  4. If it is a character from A to F, we find the case and if it is a digit we use the default option of switch case statement.
  5. After getting the value of the character, implement the formula &amp; increment the power of base (16 for hexadecimal) and then iterate the for loop for all the symbols of the given string.
  6. After exhausting the whole string using a for loop we get the equivalent decimal number as output and it is printed.

Best Approach- %x and %d Format Specifier Approach

The best approach to convert a hexadecimal number to decimal number is the %x and %d format specifier approach where user input entered in hexadecimal using %x in scanf() function and print equivalent decimal number using %d in printf() function. It is the best approach because:

  • Programmer Convenient: It is a short and very convenient way to convert hexadecimal to decimal numbers.
  • Support Built-In Function: It may be used in any in-built function such as printf(), scanf() and user defined functions.
  • Reduce Code Length: It offers reducing length of code by replacing numbers of lines using format specifiers.

Sample problems related to convert hexadecimal to decimal

Sample Problem-1: Using Approach-1

Problem Definition: Consider a company required to implement a digital calculator to convert a number system to another number system such as binary, octal, hexadecimal etc. Therefore, create an algorithm and  C  program to demonstrate hexadecimal to decimal conversions.

Solution: An algorithm for this problem is represented in the following steps.

In order to convert a hexadecimal number to a decimal number in C programming, we must first ask the user to enter the hexadecimal number to be converted, and then print its decimal equivalent.. An algorithm for this approach is represented in the following steps.

Algorithm:

Step-1: Taking hexadecimal code as an input string from the user and store into a variable.

Step-2: Check the ascii value of each character of the input string.

Step-3: Decimal number is computed according to ascii value and numbers..

To demonstrates this approach, a program is created which code is given below:

Code:

// C program to demonstrates conversion of hexadecimal to decimal using approach-1
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
	int dn=0, r, k=0, l=0;
	char hdn[25];
	printf("Enter any Hexadecimal Number for conversion into decimal number: ");
	scanf("%s", hdn);
	while(hdn[k]!='\0')
	{
    	l++;
    	k++;
	}
	l--;
	k=0;
	while(l>=0)
	{
    	r = hdn[l];
    	if(r>=48 && r<=57)
        	r = r-48;
    	else if(r>=65 && r<=70)
        	r = r-55;
    	else if(r>=97 && r<=102)
        	r = r-87;
    	else
    	{
        	printf("\n The given number is not Hexadecimal number");
        	getch();
        	return 0;
    	}
    	dn = dn + (r*pow(16, k));
    	l--;
    	k++;
	}
	printf("\n The Equivalent Decimal Value: %d", dn);
	getch();
	return 0;
}

Output:

Enter any Hexadecimal Number for conversion into decimal number: 3A
The Equivalent Decimal Value: 58

Code Explanation:

  1. Hexadecimal number taken from the user and stored into a character variable. A character array is used to hold the inputted hexadecimal number.
  2. A  while loop is created to determine the size of the character array.  Using either l– or l=l-1, reduce the length value by one after determining the length of the given hexadecimal integer. Since an array’s indexing begins at 0. Because we’re going to utilize k as a 16th exponent, initialize k to 0.
  3. Following that, decimal is allocated to dn+ (r*pow(16, k)), 0 + (9*pow(16, 0)), 0 + 9*1, or 9. When l>=0 or 1>=0 evaluates to true, program flow returns to the while loop condition and once more enters the loop.
  4. Then, dn is set to dn + (r*pow(16, k)) or 9 + (10*161) or 9+160 or 169.
  5. The value of k is increased, whereas the value of l is decreased.
  6. The identical procedure as described in the preceding steps is performed when program flow returns to the condition of the loop.
  7. Following the while loop’s termination, the dn variable, which has the specified hexadecimal number’s equivalent decimal value, is available.
  8. Print the value of the dn variable as output as a result.

Sample Problem-2: Using Approach-2

Problem Definition:  Web designers wish to make web pages in different colors. Color code is represented in hexadecimal code which requires conversion in decimal form. Therefore create an algorithm and C program to demonstrate  hexadecimal to decimal conversions.

Solution: An algorithm for this approach is represented in the following steps.

Algorithm: 

Step-1: Take a hexadecimal number from the user using %x format specifier in scanf() function.

Step-2: Decimal number is displayed using %d format specifier in printf() function .

Code:

// C program to demonstrates conversion of hexadecimal to decimal using approach-2
#include <stdio.h>
int main()
{
        	int m; // Enter value of  m as hexadecimal number input from end user
Printf(“Enter hexadecimal number”);
        	scanf("%x", &m); 
        	printf(“Decimal number is: %d", m);// print equivalent decimal number as output
      	return 0;
}

Output:

Enter hexadecimal number: 2B
Decimal number is: 43

Code Explanation:

  •  Include header file i.e. stdio.h.
  •  Ask a hexadecimal number from the user.
  • Taking hexadecimal numbers as input from the user using %x.
  • Printing the given hexadecimal number as output using %d.

Sample Problem-3:Using Approach-3

Problem Definition: Consider a computer program generating an error message with a code  where the error code is represented in hex code. To process hex code in number, it is required to convert to decimal number. Therefore create an algorithm and  C program to demonstrate how to convert a hexadecimal to decimal number.

Solution: An algorithm for this problem is represented in the following steps.

Algorithm: 

  • Step-1: Takes a hexadecimal code from the user.
  • Step-2:Calculating length of given hexadecimal number and implementing a For loop for each character / digits of given number in reverse order.
  • Step-3: Now, from right to left read each character of a given hexadecimal number and use the switch case statement for finding the value as per the input string.
  • Step-4: If it is a character from A to F, we find the case and if it is a digit we use the default option of switch case statement.
  • Step-5: After getting the value of the character, implement the formula &amp; increment the power of base (16 for hexadecimal) and then iterate the for loop for all the symbols of the given string.
  • Step-6: After exhausting the whole string using a for loop we get the equivalent decimal number as output and it is printed.

Code:

// C program to demonstrates conversion of hexadecimal to decimal using approach-3
#include <math.h>
#include <stdio.h>
#include <string.h>
int main()
{
char hdn[20];
int dn =0, k, p=0, v;
printf(“Enter the hexadecimal number (use capital letters)”);
scanf(“%s”, hdn);
for (k = (strlen(hdn) - 1); k >= 0; k--) {
switch (hdn[k]) {
case A:
v = 10;
break;
case B:
v = 11;
break;

case C:
v = 12;
break;
case D:
v = 13;
break;
case E:
v = 14;
break;
case F:
v = 15;
break;
default:
v = hdn[k] - 0x30;
}
dn = dn + (v)*pow((double)16, (double)p);
p++;
}
printf(“Decimal number is: %d“, dn); // print an equivalent decimal number
return 0;
}

Output:

Enter the hexadecimal number (use capital letters): 5C
Decimal number is: 92

Code Explanation:

  1. A hexadecimal number taken from users.
  2. Then, calculate the length of a given hexadecimal number and implement a For loop for each character / digits of given number in reverse order.
  3. Now, from right to left read each character of a given hexadecimal number and use the switch case statement for finding the value as per the input string. If it is a character from A to F, we find the case and if it is a digit we use the default option of switch case statement.
  4. Once the value of the character is computed then implement the formula &amp; increment the power of base (16 for hexadecimal) and then iterate the for loop for all the symbols of the given string.
  5. Print final result as decimal number of the given hexadecimal number.

Conclusion

C programming language allows various number systems representations and their conversions using format specifiers and other approaches. A hexadecimal number may be converted into a decimal number.

Here, several approaches for converting a hexadecimal number to decimal number were presented with an algorithm, C program, output and its explanation. A %x and %d format specifier approach is considered as the best approach because it offers a shortened and convenient way.