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) {
    uint16_t r=0;
    int i=0,len=0;
    for(int i=0;str[i]!=0;i++){
        len++;
    }
    int k=(len>2)?12:4;
    while(str[i]!=0){
        if(str[i]=='1'){
            r=(r)|(0x1<<(k-4*i));
        }
        else if(str[i]=='2'){
            r=r|(0x02<<(k-4*i));
        }
        else if(str[i]=='3'){
            r=r|(0x03<<(k-4*i));
        }
        else if(str[i]=='4'){
            r=r|(0x04<<(k-4*i));
        }
        else if(str[i]=='5'){
            r=r|(0x05<<(k-4*i));
        }
            else if(str[i]=='6'){
            r=r|(0x06<<(k-4*i));
        }
        else if(str[i]=='7'){
            r=r|(0x07<<(k-4*i));
        }
        else if(str[i]=='8'){
            r=r|(0x08<<(k-4*i));
        }
        else if(str[i]=='9'){
            r=r|(0x09<<(k-4*i));
        }
        else if(str[i]=='A' ||str[i]=='a'){
            r=r|(0x0A<<(k-4*i));
        }
        else if(str[i]=='B'||str[i]=='b'){
            r=r|(0x0B<<(k-4*i));
        }
        else if(str[i]=='C'||str[i]=='c'){
            r=r|(0x0C<<(k-4*i));
        }
        else if(str[i]=='D'||str[i]=='d'){
            r=r|(0x0D<<(k-4*i));
        } 
        else if(str[i]=='E'||str[i]=='e'){
            r=r|(0x0E<<(k-4*i));
        }
        else if(str[i]=='F'||str[i]=='f'){
            r=r|(0x0F<<(k-4*i));
        }
        else if(str[i]=='0'){
            r=r|(0x0<<(k-4*i));
        }
        i++;
    }
    return r;
}

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