Search code examples
c++stringcstringstringstreamhex

The easiest way to compare string containing integer to string containing hex


I have two strings one with integer (eg string strInt = "100") and one with hex number (eg string strHex = "0x64"). Whats the quickest/nice/safe way to compare if the values of strInt and strHex are equal(numerically)?

Need to exclude sprintf to prevent buffer overflow Also cant use snprintf - my compiler does not support c++ 11

Thank you all in advance


Solution

  • Use strtol to convert both to integer and then compare them. You can use strHex.c_str() to convert from c++ string to the c-style string required by strtol.

    Example:

    long int numHex = strtol(strHex.c_str(),NULL,16); // 16 is the base of the source
    
    long int numInt = strtol(strInt.c_str(),NULL,10);