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 res = 0;
    int i =0;

    while(str[i] != '\0')
    {
        char c = str[i];
        // printf("%c\n",c);
        if((c>='0') && (c<='9'))
        {
            res = res*16 + (c-'0');
        }
        if((c>='a') && (c<='f'))
        {
            res = res*16 + (c-'a' +10);
        }

        if((c>='A') && (c<='F'))
        {
            res = res*16 + (c-'A' +10);
        }
        // printf("%u\n",res);
        i++;
    }
    return res;
}

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