Reputation: 10324
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"?
Upvotes: 0
Views: 1132
Reputation: 283634
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.
Upvotes: 3