Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

int custom_strlen(const char *str) {
    // Your logic here
    int count = 0;
    int i = 0;
    while(str[i]!='\0'){
        count++;
        i++;
    }
    return count;
}

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    uint16_t result = 0;
    int len = custom_strlen(str);
    for(int i = 0; i < len; i++){
        uint16_t equivalent;
        if((str[i]-'0') < 10){
            equivalent = (str[i] - '0');
        }
        if(str[i]=='a' || str[i]=='A'){
            equivalent = 10;
        }
        if(str[i]=='b' || str[i]=='B'){
            equivalent = 11;
        }
        if(str[i]=='c' || str[i]=='C'){
            equivalent = 12;
        }
        if(str[i]=='d' || str[i]=='D'){
            equivalent = 13;
        }
        if(str[i]=='e' || str[i]=='E'){
            equivalent = 14;
        }
        if(str[i]=='f' || str[i]=='F'){
            equivalent = 15;
        }
        result += equivalent * (1 << (len-i-1)*4);
    }
    return result;
}

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