Convert hex string (char []) to int?

前端 未结 13 1084
栀梦
栀梦 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条回答
  •  Happy的楠姐
    2020-11-22 12:44

    Use strtol if you have libc available like the top answer suggests. However if you like custom stuff or are on a microcontroller without libc or so, you may want a slightly optimized version without complex branching.

    #include 
    
    
    /**
     * xtou64
     * Take a hex string and convert it to a 64bit number (max 16 hex digits).
     * The string must only contain digits and valid hex characters.
     */
    uint64_t xtou64(const char *str)
    {
        uint64_t res = 0;
        char c;
    
        while ((c = *str++)) {
            char v = (c & 0xF) + (c >> 6) | ((c >> 3) & 0x8);
            res = (res << 4) | (uint64_t) v;
        }
    
        return res;
    } 
    

    The bit shifting magic boils down to: Just use the last 4 bits, but if it is an non digit, then also add 9.

提交回复
热议问题