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 ans  =0;
    uint8_t low_byte = 0, high_byte=0;

    for(int i=0; str[i]!='\0';i++)
    {
        if(i<2)
        {
            if(str[i]>='A' && str[i]<='F')
            {
                high_byte = (high_byte<<4) | ((uint8_t)str[i]-65)+10;
            }


            else if(str[i]>='a' && str[i]<='f')
            {
                high_byte = (high_byte<<4) | ((uint8_t)str[i]-97)+10;
            }

            else
            {
                high_byte = (high_byte<<4) | ((uint8_t)str[i]-48);
            }
        }

        else
        {
            if(str[i]>='A' && str[i]<='F')
            {
                low_byte = (low_byte<<4) | ((uint8_t)str[i]-65)+10;
            }


            else if(str[i]>='a' && str[i]<='f')
            {
                low_byte = (low_byte<<4) | ((uint8_t)str[i]-97)+10;
            }

            else
            {
                low_byte = (low_byte<<4) | ((uint8_t)str[i]-48);
            }
        }
    }

    ans = high_byte;

    if (low_byte!=0) {
        ans = (ans<<8) | low_byte;
    }


    return ans;
}

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

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

Solving Approach

 

 

 

Loading...

Input

1A3F

Expected Output

6719