ADVERTISEMENT
ADVERTISEMENT

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.

For more details Learn: Computer Number System and its conversions.

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

C Number System Conversion Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.