Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint16_t hex_to_uint(const char *str) {
    uint32_t result =0;
    for (int i=0; i<strlen(str); i++)
    {
        char c = str[i];
        int convert_value = 0;
        if (c>= 'A'&& c<='F')
        {   
            convert_value = 10 + (c - 'A'); 
        }
        else if (c>= 'a'&& c<='f')
        {
            convert_value = 10 + (c - 'a'); 
        }
        else if (c>= '0'&& c<='9')
        {
            convert_value =  c - '0'; 
        }
        else
        {
            return 0;
        }
        result = result*16 + convert_value;
   
}
return (uint16_t) result;
}

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