#include <stdio.h>
#include <string.h>
#include <math.h>
// Function to convert a hexadecimal character to its decimal value
int hexCharToDecimal(char hexChar) {
if (hexChar >= '0' && hexChar <= '9') {
return hexChar - '0'; // For characters '0' to '9'
} else if (hexChar >= 'A' && hexChar <= 'F') {
return hexChar - 'A' + 10; // For characters 'A' to 'F'
} else if (hexChar >= 'a' && hexChar <= 'f') {
return hexChar - 'a' + 10; // For lowercase 'a' to 'f'
}
return -1; // Invalid character
}
// Function to convert Hexadecimal to Decimal
int hexadecimalToDecimal(char hex[]) {
int decimalNumber = 0;
int length = strlen(hex); // Find the length of the hex string
for (int i = 0; i < length; i++) {
int value = hexCharToDecimal(hex[i]); // Get decimal value of each hex character
decimalNumber += value * pow(16, length - i - 1); // Convert to decimal
}
return decimalNumber;
}
int main() {
char hex[20];
// Input a hexadecimal number from the user
printf("Enter a hexadecimal number: ");
scanf("%s", hex);
// Convert the hexadecimal number to decimal and display the result
int decimalNumber = hexadecimalToDecimal(hex);
printf("Decimal equivalent: %d\n", decimalNumber);
return 0;
}
Explanation:
Header Files:
#include <stdio.h>
: This is for standard input/output functions likeprintf()
andscanf()
.#include <string.h>
: This is for functions that deal with strings, likestrlen()
, which calculates the length of the hexadecimal input.#include <math.h>
: This is for thepow()
function, which is used to calculate powers of 16.
hexCharToDecimal Function:
- This function takes a single hexadecimal character (e.g., ‘A’, ‘5’) and converts it into its decimal equivalent.
- If the character is a number (
0-9
), it converts it by subtracting the ASCII value of'0'
. - If the character is a letter (
A-F
ora-f
), it converts it by subtracting the ASCII value of'A'
or'a'
, then adding10
.
hexadecimalToDecimal Function:
- This function takes the entire hexadecimal string as input (e.g., “1A3”) and converts it to decimal.
- It starts by calculating the length of the input string.
- It loops through each character of the string, converts each hex digit to its decimal equivalent using
hexCharToDecimal()
, and calculates the decimal number by multiplying each digit with the appropriate power of 16.
main Function:
- The main function takes a hexadecimal number as input from the user (as a string), calls the
hexadecimalToDecimal()
function to perform the conversion, and prints the result.
Output:
Input: 1A3
Output:
Enter a hexadecimal number: 1A3
Decimal equivalent: 419
Input: FF
Output:
Enter a hexadecimal number: FF
Decimal equivalent: 255