Convert a hexadecimal string to an integer efficiently in C?

后端 未结 16 2157
暖寄归人
暖寄归人 2020-12-01 09:31

In C, what is the most efficient way to convert a string of hex digits into a binary unsigned int or unsigned long?

For example, if I have

16条回答
  •  一向
    一向 (楼主)
    2020-12-01 10:13

    For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:

    /**
     * hex2int
     * take a hex string and convert it to a 32bit number (max 8 hex digits)
     */
    uint32_t hex2int(char *hex) {
        uint32_t val = 0;
        while (*hex) {
            // get current character then increment
            char byte = *hex++; 
            // transform hex character to the 4bit equivalent number, using the ascii table indexes
            if (byte >= '0' && byte <= '9') byte = byte - '0';
            else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
            else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
            // shift 4 to make space for new digit, and add the 4 bits of the new digit 
            val = (val << 4) | (byte & 0xF);
        }
        return val;
    }
    

    Example:

    char *z ="82ABC1EF";
    uint32_t x = hex2int(z);
    printf("Number is [%X]\n", x);
    

    Will output:

提交回复
热议问题