Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    uint16_t val = 0;
    while (*str != '\0') {
        val <<= 4;
        switch (*str) {
            case 'a': val |= 10; break;
            case 'A': val |= 10; break;
            case 'b': val |= 11; break;
            case 'B': val |= 11; break;
            case 'c': val |= 12; break;
            case 'C': val |= 12; break;
            case 'd': val |= 13; break;
            case 'D': val |= 13; break;
            case 'e': val |= 14; break;
            case 'E': val |= 14; break;
            case 'f': val |= 15; break;
            case 'F': val |= 15; break;
            default: val |= (*str-'0');
        }
        str++;
    }
    return val;
}

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