使用c ++中的字符串流将4个字符的十六进制字符串转换为带符号的short

时间:2018-03-07 20:32:45

标签: c++ bit-manipulation

之前已经问过类似的问题,我正在使用该问题的解决方案,但它不能100%正常工作。 这是我的代码:

#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 
}

s1中存储的值不应该是-1,因为如果一个(2字节)短变量的值为0xffff,那么它将是负值吗?

我没有看到我如何设置s2与我如何设置s1有什么不同,但结果却不同......

我想将上面的程序打印出来:

s1: -1
s2: -1

有人可以解释为什么程序运行后s1中的值不是-1?

2 个答案:

答案 0 :(得分:3)

问题是std::num_get::get()没有签名的短过载。流提取operator>>(short&)实际上是从字符串中读取0xffff作为long int,由于潜在的overlfow,未能将值转换为short,指定了std::numeric_limits<short>::max()的定义值并设置了std::ios_base::failbit在流上。

有关这种明确定义和预期行为的详细描述,请参见ISO / IEC 14882 [istream.formatted.arithmetic] / 2。

答案 1 :(得分:1)

最有可能的问题是

ss1 >> hex >> s1;

失败。它适合我。

更新代码以添加支票。

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

如果读入s1失败,在将其设置为有效值之前依赖其值是没有意义的。

相关问题