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 result = 0;
    char c;
    uint8_t value;

    for (int i = 0; str[i] != '\0'; i++) {
        c = str[i];

        // Convert lowercase to uppercase
        if (c >= 'a' && c <= 'f') {
            c -= 32;
        }

        // Convert character to numeric value
        if (c >= '0' && c <= '9') {
            value = c - '0';
        } else if (c >= 'A' && c <= 'F') {
            value = c - 'A' + 10;
        } else {
            // Invalid character
            return 0;
        }

        result = (result << 4) | value; // Shift left 4 bits and add new digit
    }

    return result;
}

int main() {
    char hex[10];
    scanf("%9s", hex); // Limit input to 9 characters + null terminator

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

Solving Approach

  1.  Initialize Result
  • Start with a variable result = 0 to accumulate the final number.

2. Loop Through Each Character

  • For each character c in the input string:
  • Convert lowercase to uppercase if needed (e.g., 'a''A')
    • You can do this by subtracting 32: 'a' - 32 = 'A'
  • Convert the character to its numeric value:
    • If '0' to '9': value = c - '0'
    • If 'A' to 'F': value = c - 'A' + 10
  • If the character is invalid (not a hex digit), return 0 or handle error

3. Shift and Add

  • Multiply the current result by 16 (or shift left by 4 bits): result <<= 4
  • Add the new digit: result |= value

4. Return the Result

  • After the loop, result holds the final integer value

 

 

 

 

Upvote
Downvote
Loading...

Input

1A3F

Expected Output

6719