See the documentation of:
int std::stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
in particular:
The valid integer value [of str
] consists of the following parts:
- (optional) plus or minus sign
...
...
If the minus sign was part of the input sequence, the numeric value calculated
from the sequence of digits is negated as if by unary minus in the result type.
Exceptions
In the absence of a preceding minus-sign, the string:
std::string binaryValue = "11111111111111111111111111111011";
will be interpreted in a the call:
std::stoi(binaryValue, nullptr, 2);
as a non-negative integer value in base-2 representation. But as such,
it is out of range, so std::out_of_range
is thrown:
To represent -5 as a string that your std::stoi
call will convert as you expect,
use:
std::string const binaryValue = "-101";
Live demo
If you don't want to prefix a minus sign to a non-negative base-2 numeral, or cannot do so in your real-world
situation, but wish to interpret "11111111111111111111111111111011"
as the two's complement representation of a signed integer using the std::sto*
API,
then you must first convert the string to an unsigned integer of a wide-enough
type, and then convert that unsigned value to a signed one. E.g.
#include <string>
#include <iostream>
int main()
{
auto ul = std::stoul("11111111111111111111111111111011",nullptr,2);
std::cout << ul << std::endl;
int i = ul;
std::cout << i << std::endl;
return 0;
}
Live demo