Q:

C program to convert Hexadecimal to Decimal

belongs to collection: Conversion Programs in C

0

In this exercise, we will see the C program to convert Hexadecimal to Decimal. In the interview, people ask the below questions,

  • How will you convert hexadecimal to decimal value?
  • Write a C program to convert hexadecimal number system value to decimal number system?
  • Implement logic to convert a hexadecimal number to a decimal number system?
  • Get a hexadecimal number from the user and convert it to its decimal equivalent?

Examples:

Input : 67
Output : 103
 
Input : 512
Output : 1298
 
Input: 123
Output: 291

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
#include <math.h>
#include <string.h>
#define ARRAY_SIZE  20
int main()
{
    char hex[ARRAY_SIZE];
    long long decimal = 0, base = 1;
    int i = 0, value, length;
    /* Get hexadecimal value from user */
    printf("Enter hexadecimal number: ");
    fflush(stdin);
    fgets(hex,ARRAY_SIZE,stdin);
    length = strlen(hex);
    for(i = length--; i >= 0; i--)
    {
        if(hex[i] >= '0' && hex[i] <= '9')
        {
            decimal += (hex[i] - 48) * base;
            base *= 16;
        }
        else if(hex[i] >= 'A' && hex[i] <= 'F')
        {
            decimal += (hex[i] - 55) * base;
            base *= 16;
        }
        else if(hex[i] >= 'a' && hex[i] <= 'f')
        {
            decimal += (hex[i] - 87) * base;
            base *= 16;
        }
    }
    printf("\nHexadecimal number = %s", hex);
    printf("Decimal number = %lld\n", decimal);
    return 0;
}

Output:

Enter hexadecimal number: 1A
 
Hexadecimal number = 1A
Decimal number = 26

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< C program to decimal to octal number using the mat...