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) {
    int i = 1;
    int re_vl = 0;
    int count = 0;
    while (*str)
    {
        // if(*str >= 'a' && *str <= 'z'){
        //     *str = *str + 32;
        // } 
        ++count;
        ++str;
    }
    --str;
    while (count--)
    {
        if (*str >= '0' && *str <= '9')
        {
            re_vl += (*str - '0') * i;
        }
        else if (*str >= 'A' && *str <= 'F')
        {
            re_vl += (*str - 'A' + 10) * i;
        }
        else if (*str >= 'a' && *str <= 'f')
        {
            re_vl += (*str - 'a' + 10) * i;
        }
        i *= 16;
        --str;
    }
    return re_vl;
}

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