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 number = 0;
    for(int i = 0;str[i] != '\0';i++)
    {
        number <<= 4;
        if((str[i] >= '0' && str[i]<='9') && str[i] != '\0')
        {   
            number |= (str[i] - '0');
        }
        else
        {
            if(str[i] >= 'A' && str[i] <= 'Z' && str[i] != '\0')
            {
                number |= (str[i] - 55);
            }
            else if(str[i] != '\0')
            {
                number |= (str[i] - 87);
            }
        }

        // if((str[i+1] >= '0' && str[i+1]<='9') && str[i+1] != '\0')
        // {   
            
        //     number <<= 4;
        //     number |= (str[i+1] - '0');
        // }
        // else
        // {
        //     if(str[i+1] >= 'A' && str[i+1] <= 'Z' && str[i+1] != '\0')
        //     {
        //         number <<= 4;
        //         number |= (str[i+1] - 55);
        //     }
        //     else if(str[i+1] != '\0')
        //     {
        //         number <<= 4;
        //         number |= (str[i+1] - 87);
        //     }
        // }
        if(str[i+1] == '\0')break;
    }
    return number;
}

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