How to convert hexadecimal to decimal in C

3 Answers

0 votes
#include <stdio.h>
#include <math.h>
#include <string.h>
 
int hexadecimal_to_decimal(char hex[]) {
    long decimal = 0;
    int hval, len;
 
    len = strlen(hex) - 1;
 
    for(int i = 0; hex[i] != '\0'; i++) {
        if(hex[i] >= '0' && hex[i] <= '9') {
            hval = hex[i] - 48;
        }
        else if(hex[i] >= 'a' && hex[i] <= 'f') {
            hval = hex[i] - 97 + 10;
        }
        else if(hex[i] >= 'A' && hex[i] <= 'F') {
            hval = hex[i] - 65 + 10;
        }
 
        decimal += hval * pow(16, len);
        len--;
    }  
    
    return decimal;
}
 
int main(void)
{
    char hex[8] = "1D7F";

    printf("%ld", hexadecimal_to_decimal(hex));
 
    return 0;
}

 
 
/*
run:
7551
 
*/

 



answered Aug 24, 2021 by avibootz
edited Feb 13, 2025 by avibootz
0 votes
#include <stdio.h>

int main() {
    char hex[] = "0x1D7F";
    long dec;
    
    sscanf(hex, "%x", &dec);
    // sscanf_s(hex, "%x", &dec);

    printf("%ld\n", dec);  

    return 0;
}


/*
run:

7551

*/

 



answered Feb 13, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

int main() {
    char hex[] = "0x1D7F";

    long dec = strtol(hex, NULL, 16);
    
    printf("%ld\n", dec);  

    return 0;
}


/*
run:

7551

*/

 



answered Feb 13, 2025 by avibootz

Related questions

1 answer 124 views
124 views asked Aug 24, 2021 by avibootz
1 answer 144 views
1 answer 189 views
1 answer 173 views
1 answer 186 views
1 answer 208 views
...