Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    int l = strlen(str);
    uint16_t num = 0;
    for(int x=l-1;x>=0;x--)
    {
        if(str[x]>='0' && str[x]<='9')
        {
            num+= (str[x] - '0')*(int)pow(16,l-1-x);
        }
        else if(str[x]>='A' && str[x]<='Z')
        {
            num+= (str[x] - 55)*(int)pow(16,l-1-x);
        }
        else{
            num+= (str[x] - 87)*(int)pow(16,l-1-x);
        }
    }
    return num;
}

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