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 ret = 0;

    int i = 0;
    while (str[i]) {
        ret <<= 4;
        if ('0' <= str[i] && '9' >= str[i]) {
            ret |= ((str[i] - '0') & 0xf);
        } else {
            ret |= ((str[i] - 'A' + 10) & 0xf);
        }
        i++;
    }

    return ret;
}

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

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

Solving Approach

Similar to the solution

Handling the ASCII charcters is important

 

Upvote
Downvote
Loading...

Input

1A3F

Expected Output

6719