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 result = 0;
    int i = 0;
    char c;

    // Process upto 4 characters
    while(str[i] != '\0' && i < 4){

        c = str[i];
        result <<= 4;   // Shift results left by 4 bits (Hex)

        if(c >= '0' && c <= '9'){
            result |= (c - '0');
        }
        else if(c >= 'A' && c <= 'F'){
            result |= (c - 'A' + 10);
        }
        else if(c >= 'a' && c <= 'f'){
            result |= (c - 'a' + 10);
        }
        else{
            // Invalid character for hex
            return 0;
        }

        i++;

    }

    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