【问题标题】:Convert signed short with bitset使用 bitset 转换有符号短
【发布时间】:2015-10-22 07:38:40
【问题描述】:

我想将带有 0 和 1 的字符串转换为有符号的短字符串。这项工作,但负数我有错误的价值。我认为,问题是从无符号转换为有符号。如何解决? 例子: 971 是 971, 425 是 425 , -122 是 3974 , -394 是 3702 , -2032 是 2064

bitset<12> b(binary);//binary is string of 0 and 1
 cout<<(signed short)b.to_ulong()<<"\n";

【问题讨论】:

  • 负值是什么意思?
  • @Amit 当我得到不同的数字时,我举了一个例子。我明白了,当我转换负数时会发生变化。
  • 我不明白你的评论。显示你的代码没有达到你的预期。
  • 122 + 3974 = 4096, 394 + 3702 = 4096, 2032 + 2064 = 4096,所以我假设你想要 16 位的 2 补码是正确的?

标签: c++ bitset


【解决方案1】:

在 16 位有符号整数中,负数表示为:

1xxx xxxx xxxx xxxx

正数为:

0xxx xxxx xxxx xxxx

例子:

0000 1111 1000 0110 => 3974

你需要的是一个 12 位整数,其中负数表示为:

.... 1xxx xxxx xxxx

例子:

.... 1111 1000 0110 => -122

你可以这样做:

#include <iostream>
#include <bitset>
#include <string>

using namespace std;

struct C {
    signed short b : 12; // 12 bit integer
};

int main() {
    string binary = "111110000110"; // 3974
    bitset<12> b(binary);

    struct C c = { static_cast<signed short>(b.to_ulong()) };

    cout << c.b << "\n"; // prints -122
}

【讨论】:

    【解决方案2】:

    对于从 12 位有符号整数到 12 位无符号整数的转换,您得到的值是正确的。

    例如,-122 作为有符号 12 位整数将表示为二进制 111110000110,这也是 3974 作为无符号 12 位整数的二进制表示。

    你期待什么?

    编辑

    我现在看到您正在尝试将输出转换为有符号缩写。考虑一个 short 是 16 位,而您的 bitset 是 12 位填充到一个无符号长。函数 to_ulong 不执行符号扩展(它没有上下文可以确定是否需要符号扩展,因此清除位集中表示的最高有效位),因此您将获得您的位模式表示它是一个无符号数。

    【讨论】:

      猜你喜欢
      • 2015-02-07
      • 2013-02-16
      • 2011-06-18
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 2013-10-20
      • 2011-09-29
      • 1970-01-01
      相关资源
      最近更新 更多