문제

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';
도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top