C++ convert hex string to signed integer

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

    Here's a simple and working method I found elsewhere:

    string hexString = "7FF";
    int hexNumber;
    sscanf(hexString.c_str(), "%x", &hexNumber);
    

    Please note that you might prefer using unsigned long integer/long integer, to receive the value. Another note, the c_str() function just converts the std::string to const char* .

    So if you have a const char* ready, just go ahead with using that variable name directly, as shown below [I am also showing the usage of the unsigned long variable for a larger hex number. Do not confuse it with the case of having const char* instead of string]:

    const char *hexString = "7FFEA5"; //Just to show the conversion of a bigger hex number
    unsigned long hexNumber; //In case your hex number is going to be sufficiently big.
    sscanf(hexString, "%x", &hexNumber);
    

    This works just perfectly fine (provided you use appropriate data types per your need).

提交回复
热议问题