C++ convert hex string to signed integer

前端 未结 9 1908
耶瑟儿~
耶瑟儿~ 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:19

    For a method that works with both C and C++, you might want to consider using the standard library function strtol().

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

提交回复
热议问题