Q:

C program to convert number from Hexadecimal to Decimal

0

C program to convert number from Hexadecimal to Decimal

In this program, we will read Hexadecimal Value and converts it into Hexadecimal Number System. This program is for Hexadecimal to Decimal Conversion in C.

The logic behind to implement this program - Access each digit (Use 10, 11, 12, 13, 14, 15 instead of A, B, C, D, E, F) from the Number multiply the digit by the power of 16 (for first digits from right side multiply digit with 16^0, second digits 16^1 and so on), add the result and finally you will get Decimal value of given Hexadecimal Number. Here we will multiply with the power of base and base of Hexadecimal Number is 16.

 

All Answers

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

Hexadecimal to Decimal Conversion using C program

/*program to convert number from hexadecimal to decimal*/

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

int main()
{
    char hex[32] = { 0 };
    int dec, i;
    int cnt; /*for power index*/
    int dig; /*to store digit*/

    printf("Enter hex value: ");
    gets(hex);

    cnt = 0;
    dec = 0;
    for (i = (strlen(hex) - 1); i >= 0; i--) {
        switch (hex[i]) {
        case 'A':
            dig = 10;
            break;
        case 'B':
            dig = 11;
            break;
        case 'C':
            dig = 12;
            break;
        case 'D':
            dig = 13;
            break;
        case 'E':
            dig = 14;
            break;
        case 'F':
            dig = 15;
            break;
        default:
            dig = hex[i] - 0x30;
        }
        dec = dec + (dig)*pow((double)16, (double)cnt);
        cnt++;
    }

    printf("DECIMAL value is: %d", dec);
    return 0;
}

Output:

    Enter hex value: AF6
    DECIMAL value is: 2806

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

total answers (1)

C program to convert a binary number to an octal n... >>
<< C program to convert number from Octal to Decimal...