Convert hex string (char []) to int?

前端 未结 13 1085
栀梦
栀梦 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:36

    This is a function to directly convert hexadecimal containing char array to an integer which needs no extra library:

    int hexadecimal2int(char *hdec) {
        int finalval = 0;
        while (*hdec) {
            
            int onebyte = *hdec++; 
            
            if (onebyte >= '0' && onebyte <= '9'){onebyte = onebyte - '0';}
            else if (onebyte >= 'a' && onebyte <='f') {onebyte = onebyte - 'a' + 10;}
            else if (onebyte >= 'A' && onebyte <='F') {onebyte = onebyte - 'A' + 10;}  
            
            finalval = (finalval << 4) | (onebyte & 0xF);
        }
        finalval = finalval - 524288;
        return finalval;
    }
    

提交回复
热议问题