I have an std::string that contains the response of a server. After parsing the string a bit, I come across a short. The short is big-endian and is stored in the string accordingly:
raw[0] == 0xa5;
raw[1] == 0x69;
I know this as
file << raw[0] << std::endl << raw[1];
when viewed as hex results to "0xa5 0x0a 0x69".
I write them to a short like this and then write to a file as inspired by https://stackoverflow.com/a/300837/1318909:
short x = (raw[1] << 8) | raw[0];
file << std::to_string(x);
expected result? 27045 (0x69a5).
actual result? -91 (0xffa5) <-- overflow!.
Why is this? I tested and it worked fine with a value of 2402. I also did some additional testing and it works with
short x = (raw[1] << 8) | 0xa5;
but not with
short x = (0x69 << 8) | raw[0];