C Program to Convert Hexadecimal to Decimal Value

Write a program to convert hexadecimal to a decimal value

Input Format
The input contains a Hexadecimal value

Output Format
Print its equivalent decimal value

Constraint
1<=Length<=50Sample Input 1

F

Sample Output 1

15

Code:

#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;

    scanf("%[^\n]",hex);  

    len = strlen(hex);
    len--;

    for(i=0; hex[i]!='\0'; 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("%lld", decimal);

    return 0;
}
Code language: C/AL (cal)

Leave a Comment