All submissions

Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

bool alpha(char c)
{
     if(c >= 'A' && c <= 'z')
        return true;

    return false;
}

bool lower(char c)
{
    if(c >= 'a' && c <= 'z')
        return true;

    return false;
}

bool digits(char c)
{
    if(c >= '0' && c <= '9')
        return true;
    
    return false;
}

uint16_t hex_to_uint(const char *str) {
    int i;
    uint16_t num;
    uint16_t digit;

    i = 0;
    while(str[i++]) ;

  //  printf("%d ", i);

    i = 0;
    num = 0;
    while(str[i] && str[i] != ' ')
    {
        if(alpha(str[i]))
        {
            if(lower(str[i]))
            {
                digit = str[i] - 'a' + 10;
            }
            else
                digit = str[i] - 'A' + 10;
        }
        else if(digits(str[i]))
            digit = str[i] - '0';
        else
            continue;
        
        num = num * 16 + digit;
//        printf("%u ", num);
        i++;
    }
    return num;
}

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

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

Solving Approach

 

 

 

Loading...

Input

1A3F

Expected Output

6719