简体   繁体   中英

C++ Hex to Int using Stringstream

I have a function that prints out the binary of int inputs.

When I have a hex in string form, I call the function using:

    int num = 0;
    stringstream << "0xabcd123";
    stringstream >> num;  //num becomes the decimal representation of the above hex.
    outputBinary(num);

Works perfectly.

However,

    int num = 0;
    stringstream << "0xabcd1234"; //fully filled hex value.
    stringstream >> num;  //num remains at 0.
    outputBinary(num);

Could it be that a fully filled hex value cause stringstream to overflow when converting from hex string to "num"?

The value is out of range. According to the Standard, the string is parsed using strtoll ... the value does fit in long long and is interpreted as positive. Then it checks whether it can fit in the type provided ( int ). But no, it can't, assuming your compiler has 32-bit int .

Writing

int num = 0xabcd1234;

in your source code would be trouble as well, because the literal will be given type unsigned int , and the implicit conversion to signed int is out of range, resulting in implementation-defined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM