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
    uint8_t i = 0;
    uint16_t result = 0;
 while (str[i] != '\0'){
    i++;
 }
int v = i - 1;
 for(int j = 0; j < i ; j++){
    int ram = 0;
    if( '0' <= str[j] && str[j] <= '9'){
      ram = str[j] - '0';
    }
    else if ('A' <= str[j] && str[j] <= 'F') {
            ram = str[j] - 'A' + 10;
        }
        else if ('a' <= str[j] && str[j] <= 'f') {
            ram = str[j] - 'a' + 10;
        }
        else {
            return 0; 
        }
result += (1 << (4 * v)) * ram;
v--;
 }
    return result;
}

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

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

Solving Approach

 

 

 

Loading...

Input

1A3F

Expected Output

6719