1

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';
Dangila
  • 1,434
  • 3
  • 14
  • 25
  • Look up [`std::strtol`](http://en.cppreference.com/w/cpp/string/byte/strtol) and [`std::stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol). – Some programmer dude Jun 02 '13 at 09:17
  • I think I have a similar question asked here today: [Can std::hex input format support negtive int16_t hex string with two's complement notation such as `ffff` for `-1`?](https://stackoverflow.com/questions/76319401/can-stdhex-input-format-support-negtive-int16-t-hex-string-with-twos-compleme), and I got similar answers there like the answers in this post. – ollydbg23 May 24 '23 at 10:44

1 Answers1

2

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;
Thomas Russell
  • 5,870
  • 4
  • 33
  • 68