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>
#include <string.h>
uint16_t hex_to_uint(const char *str) {
    // Your logic here
    uint16_t retval = 0;
    while(*str)
    {
        retval <<=4;
        uint8_t byte = *str++;
        if(byte >= '0' && byte <='9')
        {
            retval |= byte - '0';
        }
        else if(byte >='A' && byte <='F')
        {
            retval |= byte - 'A' + 10;
        }
        else if (byte >='a' && byte <='f')
        {
            retval |= byte - 'a' + 10;
        }
    }  
    return retval;                                                                                                 
}

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

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote