Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>
uint16_t hex_to_uint(const char *str) {
    // Your logic here
    int mul=1;
    int n=strlen(str);
    int res=0;

    for(int i=n-1;i>=0;i--)
    {
        int temp;

        if((str[i]-'0')<10)
        temp=str[i]-'0';
        else if(str[i]>='A' && str[i]<='F')
        temp=str[i]-'A'+10;
        else
        temp=str[i]-'a'+10;

        res+=(temp*mul);
        mul*=16;
    }
    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