All submissions

Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

#define isNum(x) (x>=48)&&(x<58)
#define isLittle(x) (x>=97)&&(x<103)
uint16_t hex_to_uint(const char *str) {

    
    const char *tmp = str;
    int len = 0;
    int res = 0;
    int count ;
    // Your logic here
    while(*tmp != NULL)
    {
        tmp++;
    }
    len = tmp - str;

    tmp = str;

    len-=1;
    for(int n = 0 ; n <= len ; n++)
    {
        int nibble = tmp[len-n];
        

        if(isLittle(nibble))
        {
            nibble -= (97-65);
            nibble -= 55;   
            //printf("%d %c",nibble,nibble);        
        }
        else if(isNum(nibble))
        {
            nibble -= 48;
        }
        else 
        {
            nibble -= 55;
        }
       // printf("%d ",nibble);

        res |= nibble<<((n)*4);

//        printf("%c",tmp[len]);
    }

    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