简体   繁体   中英

Converting 4 character hex string to a signed short with string streams in c++

A similar question has been asked before, and I am using the solution from that question, but it isn't working 100%. Here is my code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main () {
    string hexStr1 = "ffff";
    short s1;
    stringstream ss1;
    ss1 << hex << hexStr1;
    ss1 >> s1;

    string hexStr2 = "f";
    short s2;
    stringstream ss2;
    ss2 << hex << hexStr2;
    ss2 >> s2;

    s2 = s2 | -16;



    cout << "s1: " << s1 << "\n";  //Outputs 32767 (max short)
    cout << "s2: " << s2 << "\n";  //Outputs -1 
}

Shouldn't the value stored in s1 be -1 because if a (2-byte) short variable has the value 0xffff it would be negative one?

I don't see what is different about how I'm setting s2 vs. how I'm setting s1, but the results are different...

I would like the program above to print out:

s1: -1
s2: -1

Can anyone explain why the value in s1 is not -1 after my program runs?

The problem is that there is no signed short overload for std::num_get::get() . The stream extraction operator>>(short&) is actually reading 0xffff from the string as an long int, failing to convert the value to a short because of potential overlfow, assigning a defined value of std::numeric_limits<short>::max() and setting std::ios_base::failbit on the stream.

See ISO/IEC 14882 [istream.formatted.arithmetic]/2 for a detailed description of this well-defined and expected behaviour.

The problem most likely is that

ss1 >> hex >> s1;

fails. It does for me.

Update the code to add a check.

if ( !(ss1 >> hex >> s1) )
{
   cout << "Unable to read s1\n";
}

If reading into s1 fails, it does not make sense to rely on its value until it has been set to something valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM