Featured Post

Trie implementation in C

Hexadecimal to Integer Conversion in C

A simple implementation of converter which converts hexadecimal string to an integer.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// To convert a-f or A-F to a decimal number
int chartoint(int c)
{
    char hex[] = "aAbBcCdDeEfF";
    int i;
    int result = 0;

    for(i = 0; result == 0 && hex[i] != '\0'; i++)
    {
        if(hex[i] == c)
        {
            result = 10 + (i / 2);
        }
    }

    return result;
}

unsigned int htoi(const char s[])
{
    unsigned int result = 0;
    int i = 0;
    int proper = 1;
    int temp;

    //To take care of 0x and 0X added before the hex no.
    if(s[i] == '0')
    {
        ++i;
        if(s[i] == 'x' || s[i] == 'X')
        {
            ++i;
        }
    }

    while(proper && s[i] != '\0')
    {
        result = result * 16;
        if(s[i] >= '0' && s[i] <= '9')
        {
            result = result + (s[i] - '0');
        }
        else
        {
            temp = chartoint(s[i]);
            if(temp == 0)
            {
                proper = 0;
            }
            else
            {
                result = result + temp;
            }
        }

        ++i;
    }
    //If any character is not a proper hex no. ,  return 0
    if(!proper)
    {
        result = 0;
    }

    return result;
}

int main(void)
{
    char *endp = NULL;
    char test[20];

    printf("\nEnter a hexadecimal pattern : ");
    scanf("%s",test);
    if(htoi(test) == 0)
    {
        printf("\nEntered characters not proper Hexadecimal Number!!!\n");
        exit(0);
    }
    printf("Hex : %s\tDecimal: %d\n" ,test, htoi(test));
}

Comments