All submissions

Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint16_t mask(char ch)
{
    if(isdigit(ch))
    {
        return ch - '0';
    }
    else if(isalpha(ch))
    {
        return 10 + toupper(ch) - 'A';
    }
    else
    {
        return 0xFFFF;
    }
}

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    uint16_t res = 0;
    int i = 0;
    while(str[i] != '\0')
    {
        res <<= 4;
        uint16_t temp = mask(str[i]);
        res |= temp;
        i++;
    }
    return res;
}

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

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

Solving Approach

 

 

 

Loading...

Input

1A3F

Expected Output

6719