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

/*
Here is the math using using the steps above showing you how to convert 0X0110 to decimal.

0 × 1 = 0
1 × 16 = 16
1 × 16 × 16 = 256
0 × 16 × 16 × 16 = 0

0 + 16 + 256 + 0 = 272

*/

int main() {
    char hex[20];
    printf("Enter a hexadecimal number: ");
    scanf("%s", hex);

    long int decimal = 0;
    int i = 0;
    while (hex[i] != '\0') {
        if (hex[i] >= '0' && hex[i] <= '9')
            decimal += (hex[i] - '0') * pow(16, strlen(hex) - 1 - i);
        else if (hex[i] >= 'A' && hex[i] <= 'F')
            decimal += (hex[i] - 'A' + 10) * pow(16, strlen(hex) - 1 - i);
        else if (hex[i] >= 'a' && hex[i] <= 'f')
            decimal += (hex[i] - 'a' + 10) * pow(16, strlen(hex) - 1 - i);
        else {
            printf("Invalid hexadecimal number.\n");
            return 1;
        }
        i++;
    }

    printf("Decimal equivalent: %ld\n", decimal);
    return 0;
}
/*

When converting "A34" from hexadecimal to decimal, each digit's positional value should be considered:

A = 10
3 = 3
4 = 4

So, A34 in hexadecimal is equal to 1016^2 + 316^1 + 4*16^0 = 2560 + 48 + 4 = 2612 in decimal.



Certainly! Let's consider the input "A5" and see how the expression (hex[i] - '0') * pow(16, strlen(hex) - 1
 - i) works for each digit:

For the first digit 'A':

hex[i] is 'A'.
'0' represents the ASCII value of the character '0', which is 48.
So, 'A' - '0' equals 65 - 48, which equals 17. This represents the decimal value of 'A'.
strlen(hex) - 1 - i is 2 - 1 - 0, which equals 1. It represents the position of 'A' in the string.
Therefore, (hex[i] - '0') * pow(16, strlen(hex) - 1 - i) evaluates to 17 * pow(16, 1), which is 17 * 16 =
272.
For the second digit '5':

hex[i] is '5'.
'0' represents the ASCII value of the character '0', which is 48.
So, '5' - '0' equals 53 - 48, which equals 5. This represents the decimal value of '5'.
strlen(hex) - 1 - i is 2 - 1 - 1, which equals 0. It represents the position of '5' in the string.
Therefore, (hex[i] - '0') * pow(16, strlen(hex) - 1 - i) evaluates to 5 * pow(16, 0), which is 5 * 1 = 5.
So, for the input "A5", the expression evaluates to 272 + 5 = 277 in decimal.

*/

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: