119. Convert Hexadecimal String to Integer Without strtol or sscanf functions

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint16_t hex_to_uint(const char *str) {
    int num = 0;
    int i = 0;
    int k = 0;
    char ch = *str;
    int result = 0;
    int value = 0;
    while ((ch = *str++) != '\0')
    {
        // Convert hex character to numeric value
        if (ch >= '0' && ch <= '9')
        {
            value = ch - '0';
        }
        else if (ch >= 'A' && ch <= 'F')
        {
            value = ch - 'A' + 10;
        }
        else if (ch >= 'a' && ch <= 'f')
        {
            value = ch - 'a' + 10;
        }
        else
        {
            // Invalid character
            return 0;
        }
        result = (result << 4) | value;
    }

    return result;
}

int main() {
    char hex[10];
    scanf("%s", hex);

    printf("%u", hex_to_uint(hex));
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote