Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint8_t get_hex_char_value(char ch) {
    
    if ((ch - 48) <= 9) {
        return ch-48;
    } else if (ch >= 65 && ch <= 70) {
        return (ch-65+10);
    } else if (ch >= 97 && ch <= 102) {
        return (ch-97+10);
    }
}

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    const char * ptr = str;
    uint8_t strlen = 0;
    uint16_t result = 0;

    while (*ptr++) {
        strlen++;
    }

    for (uint8_t i = 0; i < strlen; i++) {
        uint8_t value = get_hex_char_value(str[i]);
        result |= (value << ((strlen-1)*4-i*4));
    }
    return 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