2015-10-22 37 views
1

我想用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"; 
+0

你是什么意思负值? – Amit

+0

@Amit我把例子,当我有不同的数字。我看到,当我转换负数时会发生变化。 –

+0

我不理解你的评论。显示你的代码不符合你的期望。 – Amit

回答

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

你所得到的值是用于从12的铸造正确位有符号整数到一个12位无符号整数。

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

你在期待什么?

编辑

我现在看到你正试图转换到短签订输出。考虑一个短的是16位而你的位是12位填充到一个无符号长。函数to_ulong不执行符号扩展(它没有上下文使它能够确定符号扩展是否必要,从而清除比特集中表示的最重要的比特),因此你得到了你的比特模式代表它是一个无符号数字。

相关问题