All submissions

Convert Hexadecimal String to Integer Without strtol or sscanf functions

Manual conversion by looking up ascii table.

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

uint16_t hex_to_uint(const char *str) {
    // Your logic here
    uint16_t ret_val = 0;
    char temp;
    //need to rev string b4 i/p
    //alternative
    while(*str){                     //using count as maximum digits of hex
        temp = *str;                
        if((unsigned)temp >= 'a'){        //convert lowercase 
            temp = temp - 'a' + 10;
        }
        else if((unsigned)temp >= 'A'){
            temp = temp - 'A' + 10;      //offset
        }
        else if((unsigned)temp >= '0'){
            temp = temp - '0';
        }
        ret_val <<= 4;          //multiply by correct power of 16
        ret_val |= temp;        //add current hex number
        str++;                  //increment to next
    }
    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.

 

 

Loading...

Input

1A3F

Expected Output

6719