Convert hex string (char []) to int?

前端 未结 13 1172
栀梦
栀梦 2020-11-22 12:12

I have a char[] that contains a value such as \"0x1800785\" but the function I want to give the value to requires an int, how can I convert this to an int? I have searched a

13条回答
  •  无人共我
    2020-11-22 12:56

    Or if you want to have your own implementation, I wrote this quick function as an example:

    /**
     * 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
            uint8_t 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;
    }
    

提交回复
热议问题