Convert Hexadecimal String to Integer Without strtol or sscanf functions

Code

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

uint16_t hex_string_to_int(const char *hex)
{
    int val=0,a;

  for (int i=0;hex[i];i++){
    if (hex[i]>='a') a=(hex[i]-'a') +10;
    else if (hex[i]>='A') a=(hex[i]-'A') +10;
    else a=hex[i]-'0';
    val=(val<<4)|a;
  }
  return val;
}

int main()
{
    char hex[5];   // max 4 chars + null
    scanf("%4s", hex);

    uint16_t value = hex_string_to_int(hex);
    printf("%u", value);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1A3F

Expected Output

6719