119. Convert Hexadecimal String to Integer Without strtol or sscanf functions

Back To All Submissions
Previous Submission
Next Submission

Code

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

int main()
{
    char hex[5];
    uint16_t num = 0;
    int i = 0;

    scanf("%s", hex);

    while(hex[i] != '\0')
    {
        char ch = hex[i];

        // Convert character to value
        if(ch >= '0' && ch <= '9')
        {
            num = num * 16 + (ch - '0');
        }
        else if(ch >= 'A' && ch <= 'F')
        {
            num = num * 16 + (ch - 'A' + 10);
        }
        else if(ch >= 'a' && ch <= 'f')
        {
            num = num * 16 + (ch - 'a' + 10);
        }

        i++;
    }

    printf("%u", num);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote