Convert Hexadecimal String to Integer Without strtol or sscanf functions

check bounds and convert

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

uint16_t hex_to_uint(const char* str) {
    uint16_t ret_val = 0;
    char temp;
    while(*str) {
        temp = *str;
        if(temp >= 'a' && temp <= 'f'){
            temp = temp - 'a' + 10;
        }
        else if (temp >= 'A' && temp <= 'F') {
            temp = temp - 'A' + 10;
        }
        else {
            temp = temp - '0';
        }
        ret_val = ret_val << 4;     // multiply by 16 the current hex value 
        ret_val = ret_val | temp;   // add the current bit
    
        str++;
    }

    return ret_val;
}


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

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

Solving Approach

check ascii table and filter and change values according to it, create a local char as i/p string is const . other part is loop indexing and iterating through all element while increasing power of  16.

 

 

Upvote
Downvote
Loading...

Input

1A3F

Expected Output

6719