Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint16_t pow_16(uint16_t n){
    if (n==0){
        return 1;
    }
    uint16_t sum = 1;
    while(n){
        sum *= 16;
        n--;
    }
    return sum;
}

uint16_t hex_to_uint(const char *str) {
    size_t lenght = 1;
    for (; lenght <= 4; lenght++){
        if (*(str+lenght) == '\0'){
            break;
        }
    }
    // Your logic here
    uint16_t sum = 0;
    lenght--;
    for (size_t i=0; i<(lenght+1); i++){
        char chr = *(str+i);
        uint16_t val;
        if (chr < 'A'){
            val = chr - '0';
        } else if (chr < 'a') {
            val = 10 + (chr - 'A');
        } else {
            val = 10 + (chr - 'a');
        }
        sum += val * pow_16((lenght) - i);
    }
    return sum;

}

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