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 num=0;
    uint8_t i=0;
    while(*(str+i)!='\0'){
        uint8_t ch=*(str+i);
        if ((ch>='9')&&(ch<='0'))
            ch=ch-'0';
        else if ((ch>='A')&&(ch<='F'))
            ch=ch-'A'+10;
        else if ((ch>='a')&&(ch<='f'))
            ch=ch-'a'+10;
        num=(num << 4)|(ch & 0xF);
        i++;
    }
    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