I'm trying to get boost::multiprecision to parse a negative (two's complement) hex number:
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
int main(int argc, char* argv[]) {
std::string hex_str = "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffb2e";
boost::multiprecision::int256_t signed_int(hex_str);
std::cout << signed_int << std::endl;
}
I expect this to output -1234. Unfortunately, it outputs 115792089237316195423570985008687907853269984665640564039457584007913129638702
Parsing an unsigned hex number works fine.
How can I get int256_t to interpret a hex number as a negative two's complement?
The hex conversion constructor simply doesn't parse a sign. Likewise, std::cout will refuse to print hex numbers if they're negative, and indeed
.str(..., std::ios::hex)
will throw anruntime_error
exception ("Base 8 or 16 printing of negative numbers is not supported").So you have to make it work manually, like
Here's a test program verifying all the edge cases:
Live On Coliru
Prints
PS
As a side-note, apparently numeric limits cannot be trusted, so I sidestepped them above.