All submissions

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) {
    // Your logic here
    uint16_t i, j, len=0, val=0, arr[4]= {0,0,0,0};
    uint16_t multi[4]= {4096, 256, 16, 1};

    for (i=0; (str[i] != '\0') && (i < 4); i++) {
        if ((str[i] >= 97) && (str[i] <= 102)) 
            arr[i] = str[i] -97 + 10;  // character 'a' is 10
        else if ((str[i] >= 65) && (str[i] <= 70))
            arr[i] = str[i] - 65 + 10; // 'A' is 10
        else if ((str[i] >= 48) && (str[i] <= 57))
            arr[i] = str[i] - 48;
        else
            arr[i] = 0;
           //printf("%hu\n", arr[i]);
        val= val + arr[i]* multi[i];
    }
    len = i;
    //printf("length: %u %u\n", len, val);
    for (i=0; i < (4-len); i++) {
        val = val >> 4;
    }
    return val;
}

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

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

Solving Approach

Read the characters, deciphering their digit value.

assuming four digits, calculate the value by multiplying by powers of 16

if less than four digits then right shift by 4 bits for every missing digit

 

 

Loading...

Input

1A3F

Expected Output

6719