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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 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 184 views
184 views asked Aug 24, 2021 by avibootz
1 answer 202 views
1 answer 253 views
1 answer 216 views
1 answer 253 views
...