Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

int hex_con(char c)
{
    if(c >= 65 && c<'a'){
        int temp;
        temp = c - 'A';
        temp += 10;
        return temp;
    }
    else if(c >= 'a'){
        int temp;
        temp = c - 'a';
        temp += 10;
        return temp;
    }
    else if(c <= 65)
    {
        return c -'0';
    }
}
uint16_t hex_to_uint(const char *str) {
    // Your logic here
    
    int len;
    for(len=0;str[len]!='\0';len++);

    int i ;
    int mul =1;
    int sum =0;
    for(i=len-1;i>=0;i--){
        //hex conversion
        int value ;
        value = hex_con(str[i]);
        //printf("%d ",value);
        value = value * mul;
        sum += value;
        mul *= 16;
    }
    return sum;
}

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