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) {
    uint16_t decoded = 0;
    char c;
    while (c = *str++) {
        decoded <<= 4;

        if ('0' <= c && c <= '9') {
            decoded += c - '0';
            continue;
        }
        c |= 0x20; // convert to lower case;
        if ('a' <= c && c <= 'f') {
            decoded += c - 'a' + 10;
        } else {
            // assert, error, print etc
            return 0xFFFF;
        }
    }
    return decoded;
}

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

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

Solving Approach

 

 

 

Loading...

Input

1A3F

Expected Output

6719