Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>

uint16_t hex_to_uint(const char *str) {
    int l=strlen(str),j=1,i,s=0;
    for(i=l-1;i>=0;i--){
        if(str[i]>='0'&& str[i]<='9'){
            s=s+(str[i]-'0')*j;
            j=j*16;
        }
        else if(str[i]>='A' && str[i]<='Z'){
            s=s+(str[i]-'A'+10)*j;
            j=j*16;

        }
        else{
            s=s+(str[i]-'a'+10)*j;
            j=j*16;
        }
    }
    return s;
}

int main() {
    char hex[10];
    scanf("%s", hex);

    printf("%u", hex_to_uint(hex));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1A3F

Expected Output

6719