/*
 * K&R C Programming Language
 * ---------------------------------------------------------
 * Exercise 2-3:
 * Write the function htoi(s), which converts a string
 * of hexadecimal digits (including an optional 0x or 0X)
 * into its equivalent integer value.
 * The allowable digits are 0 through 9, a through f, and A through F.
 */

#include <stdio.h>

int length(char s[]);
int is_valid_hex_char(int c);
int htoi(char hex[]);

/* test htoi function */
int
main()
{
    printf("%d\n", htoi("0x7F37"));
    printf("%d\n", htoi("0X7F37"));
    printf("%d\n", htoi("7F37"));

    printf("%d\n", htoi("0x7f37"));
    printf("%d\n", htoi("0X7f37"));
    printf("%d\n", htoi("7f37"));

    return 0;
}

/* length: returns length of s */
int
length(char s[])
{
    int i;

    for (i = 0; s[i] != '\0'; ++i)
        ;

    return i;
}

/*
 * is_valid_hex_char:
 * returns decimal equivalent of hex character c, or -1
 * for invalid hex character
 */
int
is_valid_hex_char(int c)
{
    if ( c >= '0' && c <= '9')
        return c - '0';
    else if ( c>= 'a' && c <= 'f')
        return c - 'a' + 10;
    else if (c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    else
        return -1;
}

/* htoi: return decimal equivalent of hex string */
int
htoi(char hex[])
{
    int i, len, n, d;

    i = 0;
    len = length(hex);
    if (len>=2 && hex[0]=='0' && (hex[1]=='x' || hex[1]=='X'))
        i = 2;

    n = 0;
    while (i<len && (d = is_valid_hex_char(hex[i]))!=-1) {
            n = n * 16 + d;
            i++;
    }
    return n;
}
