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>

uint8_t hexCharToInt(const char c)
{
    if (c >= '0' && c <= '9')
    {
        return c - '0';
    }

    if (c >= 'A' && c <= 'F')
    {
        return c - 'A' + 10;
    }

    if (c >= 'a' && c <= 'f')
    {
        return c - 'a' + 10;
    }

    return 0;
}

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    uint16_t value = 0;

    //Convert hex char to int
    int i = 0;
    while(str[i]) 
    {
        value = (value * 16) + hexCharToInt(str[i]);
        i++;
    }

    return value;
}

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

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote