C Program to Convert Hexadecimal Number to Decimal Number System

  • Write a C program to convert hexadecimal number to decimal number system using for loop.
  • Algorithm to convert hexadecimal number to decimal number.

Required Knowledge

Hexadecimal number system is a base 16 number system using digits 0 to 7 and A to F whereas Decimal number system is base 10 number system and using digits from 0 to 9. Given an hexadecimal number as input from user convert it to decimal number.

For Example

12AD in Hexadecimal is equivalent to 4781 in Decimal number system.

Algorithm to convert Hexadecimal to Decimal number

  • Hexadecimal digits includes characters from A to F corresponding to 10 to 15 respectively. Hence, for hex digit form A to F we will use their decimal equivalent 10 to 15 form any calculation.
  • We multiply each digit with 16i and add them, where i is the position of the Hexadecimal digit(starting from 0) from right side. Least significant digit is at position 0.

Let’s convert 12AD(hexadecimal number) to decimal number
Decimal number = 1*163 + 2*162 + 10*161 + 13*160 = 4096 + 512 + 160 + 13 = 4781

C program to convert a hexadecimal number to decimal number

C Program to Convert Hexadecimal Number to Decimal Number System

#include <stdio.h>  
#include <math.h>
#include <string.h>  
   
int main() {  
    long long decimalNumber=0;
    char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
      '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    char hexadecimal[30];  
    int i, j, power=0, digit;  
   
    printf("Enter a Hexadecimal Number\n");  
    scanf("%s", hexadecimal);  
     
    /* Converting hexadecimal number to decimal number */
    for(i=strlen(hexadecimal)-1; i >= 0; i--) {
        /*search currect character in hexDigits array */
        for(j=0; j<16; j++){
            if(hexadecimal[i] == hexDigits[j]){
                decimalNumber += j*pow(16, power);
            }
        }
        power++;
    }  
  
    printf("Decimal Number : %ld", decimalNumber);  
   
    return 0;  
}

Output

Enter a Hexadecimal Number
12AD
Decimal Number : 4781
Enter a Hexadecimal Number
2045CA
Decimal Number : 2115018