Question

By using std::hex and std::dec, it is possible to parse hexadecimal from a string and convert it to a decimal number in C++. But what if the hexadecimal number is signed?

The following code for example will result 241 which is correct if the input "F1" is unsigned hex, but the result should be -15 if the input was a signed hex. Is there a C++ function that can process signed hex values?

 int n;
 stringstream("F1") >> std::hex >> n;
 std::cout << std::dec << "Parsing \"F1\" as hex gives " << n << '\n';
Was it helpful?

Solution

When you say "signed hex" you mean if you were to represent the bitwise representation of a char in hexadecimal then F1 would be -15. However, -15 in signed hex is simply -F.

If you want to get -15 from this bitwise representation you'll have to do something like the following:

std::string szTest = "F1";
unsigned char chTest = std::stoi( szTest, nullptr, 16 );

char chTest2 = *reinterpret_cast<char*>(&chTest);

std::cout << szTest << ": " << static_cast<int>(chTest2) << std::endl;

return 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top