Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,951 questions

51,893 answers

573 users

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 110 views
110 views asked Aug 24, 2021 by avibootz
1 answer 127 views
1 answer 169 views
1 answer 161 views
1 answer 153 views
1 answer 179 views
...