C Function Converts Hex to Binary

The C listing in the text file attached to EDN BBS /DI_SIG #1436 is a simple function that converts an ASCII hexadecimal string to binary. The function htoi works very much like the standard atoi library function.


Software Design Note - htoi function

The standard C library contains functions to convert an ASCII numeric string 
to integer, long, or floating binary numbers.  However the library doesn't 
provide a simple function to convert an ASCII hexadecimal string to binary.  
That's what htoi does.

The htoi function works like the atoi library function, except it assumes the 
string is ASCII hexadecimal (upper or lower case).  Like atoi, htoi skips over 
leading whitespace (tabs or spaces), terminates on the first non-hex 
character, and has no provision for detecting overflow.

The function accepts one parameter, a pointer to the most-significant ASCII 
hex digit.  The function returns an unsigned int from 0x0000 to 0xffff (or up 
to 0xffffffff with compilers that support 32-bit integers).

Here are some examples of how to use htoi:

unsigned int nbr1, nbr2, nbr3;
char string1 [] = "  12ab  ";
char string2 [] = "\t\t  7Fxx";
char string3 [] = "Aa55Bb66 1234";
    nbr1 = htoi (string1);      nbr1 is 0x12ab
    nbr2 = htoi (string2);      nbr2 is 0x7f
    nbr3 = htoi (string3);       nbr3 is 0xbb66 (0xaa55bb66 on 32-bit systems)
    nbr3 = htoi (&string3[8]);  nbr3 is 0x1234


unsigned int htoi (const char *ptr)
unsigned int value = 0;
char ch = *ptr;


    while (ch == ' ' || ch == '\t')
        ch = *(++ptr);

    for (;;) {

        if (ch >= '0' && ch <= '9')
            value = (value << 4) + (ch - '0');
        else if (ch >= 'A' && ch <= 'F')
            value = (value << 4) + (ch - 'A' + 10);
        else if (ch >= 'a' && ch <= 'f')
            value = (value << 4) + (ch - 'a' + 10);
            return value;
        ch = *(++ptr);

Computer Page   Home Page