C program to convert Hexadecimal to Decimal number

In this article, we are going to learn how to convert Hexadecimal numbers to equivalent Decimal numbers. Here we are going to learn about two number systems one is Decimal and the other is Hexadecimal. Hexadecimal numbers are base 16 numbers and represented in numbers from 0 to 9 and A to F. Decimal numbers are base 10 numbers and represented in numbers from 0 to 9.

Step-by-step descriptive logic to convert hexadecimal to the decimal number system.

  • Input a hexadecimal number from the user. Store it in some variable hex.
  • Initialize decimal = 0, digit = length_of_hexadecimal_digit – 1 and i = 0.
  • Run a loop for each hex digit. Which is the loop structure should look like for(i=0; hex[i]!=’\0′; i++).
  • Inside the loop find the integer value of hex[i]. Store it in some variable say val.
  • Convert the hex to a decimal using decimal = decimal + (val * 16 ^ digit). Where val = hex[i].

C program to convert Hexadecimal to Decimal number


 
#include <stdio.h>
#include <math.h>
#include <string.h>

int main()
{
    char hex[17];
    long long decimal, place;
    int i = 0, val, len;

    decimal = 0;
    place = 1;

    /* Input hexadecimal number from user */
    printf("Enter any hexadecimal number: ");
    gets(hex);

    /* Find the length of total number of hex digit */
    len = strlen(hex);
    len--;

    /*
     * Iterate over each hex digit
     */
    for(i=0; hex[i]!='
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
char hex[17];
long long decimal, place;
int i = 0, val, len;
decimal = 0;
place = 1;
/* Input hexadecimal number from user */
printf("Enter any hexadecimal number: ");
gets(hex);
/* Find the length of total number of hex digit */
len = strlen(hex);
len--;
/*
* Iterate over each hex digit
*/
for(i=0; hex[i]!='\0'; i++)
{
/* Find the decimal representation of hex[i] */
if(hex[i]>='0' && hex[i]<='9')
{
val = hex[i] - 48;
}
else if(hex[i]>='a' && hex[i]<='f')
{
val = hex[i] - 97 + 10;
}
else if(hex[i]>='A' && hex[i]<='F')
{
val = hex[i] - 65 + 10;
}
decimal += val * pow(16, len);
len--;
}
printf("Hexadecimal number = %s\n", hex);
printf("Decimal number = %lld", decimal);
return 0;
}
'; i++) { /* Find the decimal representation of hex[i] */ if(hex[i]>='0' && hex[i]<='9') { val = hex[i] - 48; } else if(hex[i]>='a' && hex[i]<='f') { val = hex[i] - 97 + 10; } else if(hex[i]>='A' && hex[i]<='F') { val = hex[i] - 65 + 10; } decimal += val * pow(16, len); len--; } printf("Hexadecimal number = %s\n", hex); printf("Decimal number = %lld", decimal); return 0; }

Output

Enter any hexadecimal number: 2f
Hexadecimal number = 2f
Decimal number = 47