Convert hex string (char []) to int?

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

    So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.

    int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
    {
        int _result = 0;
        DWORD _resultPtr = reinterpret_cast(&_result);
        for(int i=0;i= 0x30 && _firstChar <= 0x39)
                _multiplierFirstValue = _firstChar - 0x30;
            else if(_firstChar >= 0x41 && _firstChar <= 0x46)
                _multiplierFirstValue = 10 + (_firstChar - 0x41);
    
            char _secndChar = _hex[offset + i + 1];
            if(_secndChar >= 0x30 && _secndChar <= 0x39)
                _addonSecondValue = _secndChar - 0x30;
            else if(_secndChar >= 0x41 && _secndChar <= 0x46)
                _addonSecondValue = 10 + (_secndChar - 0x41);
    
            *(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
        }
        return _result;
    }
    

    Usage:

    char *someHex = "#CCFF00FF";
    int hexDevalue = hexToInt(someHex, 1, 8);
    

    1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.

    Speedtest (1.000.000 calls):

    strtol ~ 0.4400s
    hexToInt ~ 0.1100s
    

提交回复
热议问题