119. Convert Hexadecimal String to Integer Without strtol or sscanf functions

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint16_t hex_to_uint(const char *str) {
    // 1. Length of string
    int length;
    while(str[length]!=0){
        length++;
    }

    int hex_weight=1; //*16
    long int cur_value = 0;
    for(int i=0;i<length;i++){
        //Convert char to numerical value in reverse order
        //A-F ..
        if(str[length-1-i] >= '0' && str[length-1-i] <= '9'){
            cur_value += (str[length-1-i]-'0') * hex_weight;
        }
        else if(str[length-1-i] >= 'A' && str[length-1-i] <= 'F'){
            cur_value += (str[length-1-i]- 55) * hex_weight;
        }
        else if(str[length-1-i] >= 'a' && str[length-1-i] <= 'f'){
            cur_value += (str[length-1-i]-87) * hex_weight;
        }
        hex_weight*=16; 

    }


    return cur_value;
}

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

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote