Search code examples
cconverters

Hexadecimal String Conversion to Integer in C


I have a 4 byte string of hex characters and I want to convert them into a 2 byte integer in c.

I cannot use strtol, fprintf or fscanf.

I want this:-

unsigned char *hexstring = "12FF";

To be converted to this:-

unsigned int hexInt = 0x12FF

Solution

  • EDIT: Doh, just read azmuhak's suggested link. This is definitely a duplicate of that question. The answer in azmuhak's link is also more complete because it deals with "0x" prefixes...

    The following will work with out using the standard library... See it on ideone here

    #include <stdio.h>
    
    #define ASCII_0_VALU 48
    #define ASCII_9_VALU 57
    #define ASCII_A_VALU 65
    #define ASCII_F_VALU 70
    
    unsigned int HexStringToUInt(char const* hexstring)
    {
        unsigned int result = 0;
        char const *c = hexstring;
        char thisC;
    
        while( (thisC = *c) != NULL )
        {
            unsigned int add;
            thisC = toupper(thisC);
    
            result <<= 4;
    
            if( thisC >= ASCII_0_VALU &&  thisC <= ASCII_9_VALU )
                add = thisC - ASCII_0_VALU;
            else if( thisC >= ASCII_A_VALU && thisC <= ASCII_F_VALU)
                add = thisC - ASCII_A_VALU + 10;
            else
            {
                printf("Unrecognised hex character \"%c\"\n", thisC);
                exit(-1);
            }
    
            result += add;
            ++c;
        }
    
        return result;  
    }
    
    int main(void) 
    {
        printf("\nANSWER(\"12FF\"): %d\n", HexStringToUInt("12FF"));
        printf("\nANSWER(\"abcd\"): %d\n", HexStringToUInt("abcd"));
    
        return 0;
    }
    

    The code could be made more efficient and I use the toupper library function, but you could easily implement that yourself...

    Also, this won't parse strings beginning with "0x"... but you could add a quick check for that at the beginning of the function and just chew up those characters...