C++ convert hex string to signed integer

前端 未结 9 1903
耶瑟儿~
耶瑟儿~ 2020-11-22 03:08

I want to convert a hex string to a 32 bit signed integer in C++.

So, for example, I have the hex string \"fffefffe\". The binary representation of this is 111111

9条回答
  •  遇见更好的自我
    2020-11-22 03:33

    Working example with strtoul will be:

    #include 
    #include 
    using namespace std;
    
    int main() { 
        string s = "fffefffe";
        char * p;
        long n = strtoul( s.c_str(), & p, 16 ); 
        if ( * p != 0 ) {  
            cout << "not a number" << endl;
        }    else {  
            cout << n << endl;
        }
    }
    

    strtol converts string to long. On my computer numeric_limits::max() gives 0x7fffffff. Obviously that 0xfffefffe is greater than 0x7fffffff. So strtol returns MAX_LONG instead of wanted value. strtoul converts string to unsigned long that's why no overflow in this case.

    Ok, strtol is considering input string not as 32-bit signed integer before convertation. Funny sample with strtol:

    #include 
    #include 
    using namespace std;
    
    int main() { 
        string s = "-0x10002";
        char * p;
        long n = strtol( s.c_str(), & p, 16 ); 
        if ( * p != 0 ) {  
            cout << "not a number" << endl;
        }    else {  
            cout << n << endl;
        }
    }
    

    The code above prints -65538 in console.

提交回复
热议问题