🔄📚Intermediate
Hexadecimal to Decimal Conversion
Convert hex to decimal
Convert hexadecimal (base 16) to decimal (base 10).
Program Code
hex_to_decimal.c
C
1#include <stdio.h>2#include <string.h>3#include <ctype.h>4#include <math.h>56int hexToDecimal(char hex[]) {7 int decimal = 0;8 int len = strlen(hex);9 10 for (int i = 0; i < len; i++) {11 int digit;12 char ch = toupper(hex[i]);13 14 if (ch >= '0' && ch <= '9') {15 digit = ch - '0';16 } else if (ch >= 'A' && ch <= 'F') {17 digit = ch - 'A' + 10;18 } else {19 return -1; // Invalid20 }21 22 decimal += digit * pow(16, len - 1 - i);23 }24 25 return decimal;26}2728int main() {29 char hex[] = "1A3";30 31 printf("Hexadecimal: %s\n", hex);32 printf("Decimal: %d\n", hexToDecimal(hex));33 34 // Using scanf with format specifier35 int num;36 sscanf("FF", "%x", &num);37 printf("\nHex FF = Decimal %d\n", num);38 39 return 0;40}Output
Hexadecimal: 1A3
Decimal: 419
Hex FF = Decimal 255
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials